문제

For this code:

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;
    }
}

My compiler threw this error at me:

warning: control reaches end of non-void function [-Wreturn-type]

I know it is undefined behavior to have no return statement in a function, but is it undefined behavior to not have a return statement for all control paths? Thanks in advance.

도움이 되었습니까?

해결책

In your case, the return value of fun is not void, so, yes, it's undefined behavior.

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.

다른 팁

Reason is that you have called your fun function with incorrect value, not Red, Blue or Green. You can change your code to

int fun(Colors color)
{
    switch (color)
    {
        case Colors::Red: return 0;
        case Colors::Blue: return 1;
        case Colors::Green: return 2;
        default: return -1; // Unknown color here!
    }
}

It's okay to not have a return statement in a function, if it returns void. However, for a function not returning void it's always undefined behavior to not have a valid return value from any execution path.

So in your case, you need a return with a value after the switch.

Note that you don't need a default case if you list all the possible cases in the switch statement.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top