gpt4 book ai didi

c++ - 控制到达非空函数未定义行为的结尾

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:24:42 24 4
gpt4 key购买 nike

对于这段代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com