Getting a bunch of crosses initialization error

后端 未结 2 612
挽巷
挽巷 2020-12-01 02:32

I have this snippets of code taken from a downloaded example:

bool ChatServer::event(QEvent * event)
{
    if(event->type() == QEvent::User)
    {
                


        
相关标签:
2条回答
  • 2020-12-01 03:23

    The C++ standard says:

    It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer.

    The cases in switch are considered as a "jump".

    Just put all objects and variables initializations before your switch, and everything will be fine.

    Consider this code:

    switch(k)
    {
        case 1:
            int t = 4;
        break;
        default:
        break;
    }
    

    It will cause a "crosses initialization" error, because it is possible to skip the initialization of t, but after that it will still be in scope, even though it was never created in the first place.

    Now consider this:

    switch(k)
    {
        case 1:
        {
            int t = 4;
        }
        break;
        default:
        break;
    }
    

    Here, you will not have the error, because the variable is inside a block, and will die at the end of the block ( at the closing { ), so after that it will not be in scope in any case.

    To fix the first case, you just need to do:

    int t = 0;
    switch(k)
    {
        case 1:
            t = 4;
        break;
        default:
        break;
    }
    
    0 讨论(0)
  • 2020-12-01 03:25

    Am porting some old code from C to C++, with lots of goto's (to error exits). This issue also arises outside of switch statements.

    My simple work-around for gcc/g++ (tested with arm-linux-androideabi-gcc v4.6):

    If you have

    goto err_exit;
    int a = 1;
    

    it complains.

    Add -fpermissive to your command line, and substitute:

    goto err_exit;
    int a;
    a = 1;
    

    no complaints.

    0 讨论(0)
提交回复
热议问题