Compile Error with: switch, "expected expression before"

IphoneObjective CCocoaXcodexcode3.2

Iphone Problem Overview


Cut to the chase I have recreated my problem as it is fairly self explanatory.

this complies without error:

switch (n) {
	case 1:
		NSLog(@"");
		NSString *aStr;
		break;
	default:
		break;
	}

this compiles with error and it's only missing the NSLog():

switch (n) {
	case 1:
		NSString *aStr;
		break;
	default:
		break;
	}

it throws an error at compile "Expected expression before 'NSString'"

Am I missing something here?

Iphone Solutions


Solution 1 - Iphone

In normal C you'd have to enclose this in brackets in both cases. I suspect this may fix your problem:

case 1:
{
    NSLog(@"");
    NSString *aStr;
    break;
}

See this SO question for more info.

Another way to get around this problem is to put a statement between the case label and the first declaration as you've done in your working example above. See the comments and Quinn Taylor's answer for more info.

Solution 2 - Iphone

You can't declare a variable as the first statement in a case without brackets, and in many other contexts in C-based languages. See https://stackoverflow.com/questions/1231198/ for details.

Solution 3 - Iphone

case 0: {
    Loading my nib file;
    break; 
}
case 1: {
    Loading another nib file;
    break; 
}
Note that if you don't have an assignment (x = y) right after the case it won't be a problem. For example:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRossView Question on Stackoverflow
Solution 1 - IphoneDan OlsonView Answer on Stackoverflow
Solution 2 - IphoneQuinn TaylorView Answer on Stackoverflow
Solution 3 - Iphonekiran kumarView Answer on Stackoverflow