当函数缺少返回值时,编译器生成警告但不是错误? [英] When a function missing the return value, the compiler generates a warning but not an error?
问题描述
这里是一个c ++函数:
Here is a c++ function:
int FuncWithoutReturn()
{
int var = 10;
++var;
// No return value here !!!
}
在MSVC中,编译器生成错误:
In MSVC, compiler generates error:
错误C4716:'FuncWithoutReturn':必须返回一个值。
error C4716: 'FuncWithoutReturn' : must return a value.
XCode 5,编译器只是发出警告:
But in XCode 5, the compiler just spits a warning:
控制到达非void函数结束
Control reaches end of non-void function
在运行时如果我很幸运,应用程序崩溃。我知道这是一个愚蠢的错误,但它会是好的,编译器产生错误在第一位。
In runtime if I am lucky, the app crashes. I know it is a stupid error but it would be good that the compiler yields an error in first place.
只是想知道任何人都知道为什么XCode认为这是一个警告而不是错误。
Just wondering anyone knows WHY XCode think it is a warning instead of an error.
推荐答案
您可以使用 -Werror = return-type
发出警告和错误,在我原来的评论中忘记了。您可以直播。
You can use -Werror=return-type
to make that warning and error, in my original comment I forgot that. You can see it live.
这是 ang中的一个选项和 gcc ,据我了解 XCode
可以使用任何一个。
This is both an option in clang and gcc, as far as I understand XCode
can use either one.
下降的值结束返回函数是未定义的行为,我们可以通过访问草稿C ++标准部分 6.6.3
return语句段落 2 ,表示:
Falling off the end of value returning function is undefined behavior, we can see this by going to the draft C++ standard section 6.6.3
The return statement paragraph 2 which says:
[...]相当于没有价值的回报;这会导致返回值函数中的未定义行为。
[...]Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
未定义行为不需要诊断(警告或错误),尽管在许多情况下编译器将提供一个。
Undefined Behavior does not require a diagnostic(warning or error), although in many cases compilers will provide one.
这篇关于当函数缺少返回值时,编译器生成警告但不是错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!