JoBu1324
JoBu1324

Reputation: 7769

Can I declare variables inside an Objective-C switch statement?

I think I'm going blind, because I can't figure out where the syntax error is in this code:

if( cell == nil ) {
    titledCell = [ [ [ TitledCell alloc ] initWithFrame:CGRectZero
        reuseIdentifier:CellIdentifier ] autorelease
    ];

    switch( cellNumber ) {
        case 1:
            NSString *viewDataKey = @"Name";
etc...

When I try to compile it, I'm getting an Error: syntax error before '*' token on the last line.

Sorry for such a basic question, but what am I missing?

Upvotes: 58

Views: 22151

Answers (6)

egarlock
egarlock

Reputation: 579

You can create a variable within a switch statement but you will have to create it within a block so that the scope of that variable is defined.

Example:

switch(number){

    case 1:
        {
            // Create object here
            // object is defined only for the scope of this block
        }
        break;
    case 2:
        {
            // etc.
        }
        break;
    default:
        break;

}

Upvotes: 2

lin zheng
lin zheng

Reputation: 40

How to solve the warning:

1.Insert one ; in the first line of your case block

2.Put codes inside braces

Upvotes: 0

Chuck
Chuck

Reputation: 237110

You can't declare a variable at the beginning of a case statement. Make a test case that just consists of that and you'll get the same error.

It doesn't have to do with variables being declared in the middle of a block — even adopting a standard that allows that won't make GCC accept a declaration at the beginning of a case statement. It appears that GCC views the case label as part of the line and thus won't allow a declaration there.

A simple workaround is just to put a semicolon at the beginning of the case so the declaration is not at the start.

Upvotes: 20

Aragorn
Aragorn

Reputation: 839

In C you only can declare variables at the begining of a block before any non-declare statements.

{
   /* you can declare variables here */

   /* block statements */

   /* You can't declare variables here */
}

In C++ you can declare variables any where you need them.

Upvotes: 4

ephemient
ephemient

Reputation: 204926

I don't have a suitable Objective-C compiler on hand, but as long as the C constructs are identical:

switch { … } gives you one block-level scope, not one for each case. Declaring a variable anywhere other than the beginning of the scope is illegal, and inside a switch is especially dangerous because its initialization may be jumped over.

Do either of the following resolve the issue?

NSString *viewDataKey;
switch (cellNumber) {
    case 1:
        viewDataKey = @"Name";
    …
}

switch (cellNumber) {
    case 1: {
        NSString *viewDataKey = @"Name";
        …
    }
    …
}

Upvotes: 74

Phil Miller
Phil Miller

Reputation: 38138

Might it not be valid to declare a variable within a switch block?

Upvotes: 1

Related Questions