Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a type declaration be made in a Switch statement?

I am using XCode 4.0.2 for a iOS4 project.

I have a standard "Switch" statement

switch (i) {
    case 0:
        int a = 0;
    break
    ...
}

This give me an error "Expected expression" on int a = 0;.

It is very strange that "Switch" is working fine if I precede type declaration with a simple statement like this

switch (i) {
    case 0:
        b = 0;
        int a = 0;
    break
    ...
}  

in this case the compiler gives no error (only a "unused variable a" warning).

How can that be?

Thank you.

like image 504
boscarol Avatar asked Jul 15 '11 11:07

boscarol


3 Answers

Try something like

switch (i) {
    case 0:
    {
        int a = 0;
    }
    break
    ...
}
like image 196
Mihai Fratu Avatar answered Oct 22 '22 04:10

Mihai Fratu


Just enclose the case statement in curly brackets:

switch (i) {
    case 0: {
        int a = 0;
        break; 
    }

    ...
}
like image 38
Jonathan. Avatar answered Oct 22 '22 04:10

Jonathan.


You need to open a new scope with { } in order to declare new variables:

switch (i) {
    case 0: {
        int a = 0;
        break;
    }
}
like image 1
DarkDust Avatar answered Oct 22 '22 04:10

DarkDust