我需要将strtol的结果强制转换为int吗? [英] Do I need to cast the result of strtol to int?
问题描述
以下代码在g ++ 4.1.1和 -Wall
中不会给出警告。
int octalStrToInt(const std :: string& s)
{
return strtol(s.c_str(),0,8);
}
我期望收到警告,因为strtol返回了 long int
,但我的函数仅返回普通的 int
。其他编译器可能会在此处发出警告吗? 在这种情况下,我应该将返回值强制转换为int吗?
需要使用-Wconversion标志来打开这些警告。但是,它不会发出 long -> int 的警告,因为它们与GCC的大小相同(该值不会因转化而改变)。但是如果您转换例如 long -> short
,我想只是简单地进行强制转换不会推荐,因为那样可以掩盖错误的可能性。在您检查了这样的强制类型转换不会修改该值以安抚编译器之后,就可以了。The following code does not give a warning with g++ 4.1.1 and -Wall
.
int octalStrToInt(const std::string& s)
{
return strtol(s.c_str(), 0, 8);
}
I was expecting a warning because strtol returns a long int
but my function is only returning a plain int
. Might other compilers emit a warning here? Should I cast the return value to int in this case as a good practice?
You may need the -Wconversion flag to turn these warnings on. However, it won't warn about long -> int, since they are the same size with GCC (the value won't change because of the conversion). But it would if you convert for example long -> short
I suppose simply doing a cast would not be recommended, since that would just cover up the possibility of bugs. It would be OK after you have checked that such a cast won't modify the value to appease the compiler.
这篇关于我需要将strtol的结果强制转换为int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!