这是一个 C++ 函数:
int FuncWithoutReturn()
{
int var = 10;
++var;
// No return value here !!!
}
在 MSVC 中,编译器生成错误:
error C4716: 'FuncWithoutReturn' : must return a value.
但在 XCode 5 中,编译器只是发出警告:
Control reaches end of non-void function
如果幸运的话,在运行时,应用程序会崩溃。我知道这是一个愚蠢的错误,但编译器首先产生错误会很好。
只是想知道为什么 XCode 认为这是警告而不是错误。
最佳答案
您可以使用 -Werror=return-type
来发出警告和错误,在我原来的评论中我忘记了。可以看看live .
这都是 clang 中的一个选项和 gcc ,据我所知,XCode
可以使用任何一个。
掉落值返回函数的结尾是undefined behavior ,我们可以通过转到 draft C++ standard 来查看。 6.6.3
返回语句 2 段说:
[...]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.
未定义行为不需要诊断(警告或错误),尽管在许多情况下编译器会提供诊断。
关于c++ - 当函数缺少返回值时,编译器会生成警告而不是错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870290/