对于这段代码:
enum class Colors { Red, Green, Blue };
int fun(Colors color)
{
switch (color)
{
case Colors::Red: return 0;
case Colors::Blue: return 1;
case Colors::Green: return 2;
}
}
我的编译器向我抛出这个错误:
warning: control reaches end of non-void function [-Wreturn-type]
我知道函数中没有返回语句是未定义行为,但是所有控制路径都没有返回语句是未定义行为吗?提前致谢。
最佳答案
在你的例子中,fun
的返回值不是 void
,所以,是的,它是未定义的行为。
C++11 6.6.3 The
return
statement[...] 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/22268667/