Why when I use a static variable in switch case it gives errors: "initialization of" counter "is skipped by 'case' label", "initialization of" counter "is skipped by 'default' label"

int num = 1; switch (num) { case 1: static int counter = 0; cout << "COUNTER = " << counter; counter++; break; case 0: cout << "000"; break; default: cout << "Error"; break; } 

This error can be corrected by moving the static variable to the bottom, but why c ++ does not allow this situation.

    1 answer 1

    The fact is that the C / ++ switch / case construct is a modified goto , and case blocks do not create a new scope. Accordingly, the counter variable can be used in the case 0 and default blocks, but this variable is initialized only when the case 1 block is executed. This can lead to the couter variable couter without initialization.

    You must manually create a new scope. Now the counter not visible from other blocks and cannot be accidentally used inside them:

     case 1: { static int counter = 0; cout << "COUNTER = " << counter; counter++; break; } 

    Or bring this variable out, then counter can be used in other blocks, but will always be initialized.

     static int counter = 0; switch (num)