Is it possible to write statements after return?

后端 未结 5 1394
遇见更好的自我
遇见更好的自我 2021-01-20 18:13

Is the return statement the last statement inside main or is it possible to write statements after return?

#include 

        
5条回答
  •  渐次进展
    2021-01-20 18:29

    is it possible to write statements after return?

    It is possible and valid to write more statements after the return. With gcc and Clang, I don't get a warning, even with the -Wall switch. But Visual Studio does produce warning C4702: unreachable code for this program.


    The return statement terminates the current function, be it main or another function.

    Even though it is valid to write, if the code after the return is unreachable the compiler may eliminate it from the program as per the as-if rule.


    You could have the return statement executed conditionally and you could have multiple return statements. For example:

    int main() {
        bool all_printed{false};
        cout << "Hello" << endl;
        if (all_printed) 
            return 0;
        cout << "Bye" << endl;
        all_printed = true;
        if (all_printed) 
            return 0;
    }
    

    Or, you could use a goto before and after the return and some labels, to execute the return statement after the second output:

    int main() {
    
        cout << "Hello" << endl;
        goto print;
    
    return_here:
        return 0;
    
    print:
        cout << "Bye" << endl;
        goto return_here;
    }
    

    Prints:

    Hello
    Bye
    

    Another solution, linked to in this answer, would be to use RAII to print after the return:

    struct Bye {
        ~Bye(){ cout << "Bye" << endl; } // destructor will print
    };
    
    int main() {
        Bye bye;
        cout << "Hello" << endl;
        return 0; // ~Bye() is called
    }
    

提交回复
热议问题