简体   繁体   English

为什么用switch语句函数不需要返回

[英]Why function with switch statement doesn't need return

enum MyEnum
{
    A,
    B,
}

MyEnum Foo(int i)
{
    MyEnum mx;
    switch(i)
    {
    case 1:
        {
            mx = A;
        }break;
    case 2:
        {
            mx = B;
        }break;
    default:
        {
            throw std::exception("ERROR");
        }
    }
}

int Main()
{
    MyEnum myEnum = Foo(1);
    return 0;
}

Without 'return' in Foo( ), This code can be compiled and run in VS2010. 在Foo()中没有'return',这段代码可以在VS2010中编译和运行。 Is it compiler bug? 是编译器错误吗?

VS2010 screenshot to confirm that it can be run VS2010截图确认它可以运行

It is not a compiler bug. 它不是编译器错误。 A missing return doesn't require a diagnostics from the compiler (but the compiler might emit one), and it leads to undefined behavior - anything can happen. 缺少的返回不需要编译器的诊断(但编译器可能会发出一个),并导致未定义的行为 - 任何事情都可能发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM