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

标签 c++ enums return switch-statement undefined-behavior

对于这段代码:

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/

相关文章:

c++ - 尝试将整数解析为字符串 (qi::as_wstring)

c++ - 为新的 ArrayFire 版本调整 MatchedFilter 算法时出现问题

c++ - 从 0 到 8 之间随机选择一个数字,一个数字一个数字,直到没有数字可以选择,然后重新开始

c++ - C 中的指针和枚举

sql - 在sql中运行累积返回

javascript - 从嵌套函数返回当前 URL - Chrome 扩展

Swift 跳过 "else if"

c++ - 删除还是不删除(调用函数)?

c++ - 为什么它在这里使用 void** ?

ruby-on-rails - 使用 rspec 检查错误的枚举