1

Possible Duplicate:
Why can't variables be declared in a switch statement?

I saw somethere that in C the initialization of a variable can be skipped by a jump statement, as in the following example:

/* valid in C but not C++ */

int main()
{
    switch (1)
    {
    case 0:
        int foo = 0;
        break;
    case 1:
        ++foo;
    }

    return 0;
}

But when i try to compile it with Comeau compiler there are errors:

"ComeauTest.c", line 8: error: a declaration cannot have a label int foo = 0; ^

"ComeauTest.c", line 5: warning: transfer of control bypasses initialization of: variable "foo" (declared at line 8) switch (1) ^

Community
  • 1
  • 1
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • 1
    To get around that you can use the scope braces. That is put '{' before the int foo = 0 and put '}' after int foo = 0; – dchhetri Aug 30 '12 at 03:18
  • Yeah, i know. I want to know why i can't do it in C, while in the thread http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement all says that it's possible – FrozenHeart Aug 30 '12 at 03:22
  • 1
    @NikitaTrophimov: Add a semicolon after `case 0:;`. Declarations are not allowed directly after the label. – Jesse Good Aug 30 '12 at 03:50

0 Answers0