Domanda

I came across very strange problem today. Lets concider the following code:

int llex(){
    cout<<"enter 1"<<endl;
    char32_t c = U'(';
    cout<<(c==U'#')<<endl;
    switch(c){
    case U'#':
        cout<<"enter 2"<<endl;
        return 5;
    default:
        break;
    }
}

int main( int argc, char** argv)
{
    cout<<"enter 1"<<endl;
    char32_t c = U'(';
    cout<<(c==U'#')<<endl;
    switch(c){
    case U'#':
        cout<<"enter 2"<<endl;
        return 5;
    default:
        break;
    }

    cout << "------------" << endl;
    llex();
}

And the output is:

enter 1
0
------------
enter 1
0
enter 2

Please note that the code in main is IDENTICAL to the code in llex function. Why they output different results? (I'm using C++11 on clang).

È stato utile?

Soluzione

Your llex() function is supposed to always return a value, but it does not. This is undefined behavior if control flow does not hit the return statement. Per paragraph 6.6.3/2 of the C++11 standard:

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.

Unless you fix this, you cannot make any assumptions on your program, nor have expectations about it.

For instance, I cannot reproduce the behavior in this fixed live example.

Altri suggerimenti

You are missing an end-of-the-function return statement and a closing curly braces for your switch in the function.

int llex(){
    cout<<"enter 1"<<endl;
    char32_t c = U'(';
    cout<<(c==U'#')<<endl;
    switch(c){
    case U'#':
        cout<<"enter 2"<<endl;
        return 5;
    default:
        break;
    }
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top