Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating new object within switch block - why does it fail?

Tags:

objective-c

Why does

switch ([document currentTool]) {
    case DrawLine:
        NSBezierPath * testPath = [[NSBezierPath alloc]init];
        //...rest of code that uses testPath....

result in

error:syntax error before "*" token

for testPath?

like image 818
Joe Avatar asked Dec 31 '22 07:12

Joe


1 Answers

You can't instantiate an object inside a case statement unless you put it inside a new scope. This is because otherwise you could do something like this:

switch( ... ) {
    case A:
       MyClass obj( constructor stuff );
       // more stuff
       // fall through to next case
    case B:
       // what is the value of obj here? The constructor was never called
    ...
}

If you want the object to last for the duration of the case, you can do this:

switch( ... ) {
    case A: {
       MyClass obj( constructor stuff );
       // more stuff
       // fall through to next case
    }
    case B:
       // obj does not exist here
    ...
}

This is the same in Objective C as well as C and C++.

like image 121
Graeme Perrow Avatar answered Feb 23 '23 12:02

Graeme Perrow