Can a type declaration be made in a Switch statement?

I am using Xcode 4.0.2 for an iOS4 project.

I have a standard switch statement

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

This will give me the "Expected Expression" error on int a = 0 ;.

It’s very strange that β€œSwitch” works fine if I precede a type declaration with a simple statement like

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

in this case, the compiler does not give an error (only the warning "unused variable a").

How can it be?

Thanks.

+7
source share
4 answers

Try something like

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

Just enclose the case statement in braces:

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

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

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

You can declare type variables

 switch (i) { case 0: { //User brackets int a = 0; } break ... } 
0
source

All Articles