Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected Expression before ... In Switch Statement [duplicate]

Tags:

c

objective-c

I am getting a compilation error in this block of code:

switch(event) {
    case kCFStreamEventHasBytesAvailable:
        UInt8 buf[BUFSIZE];
        CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);
        if (bytesRead > 0) {
            handleBytes(buf, bytesRead);
        }
        break;
    case kCFStreamEventErrorOccurred:
        NSLog(@"A Read Stream Error Has Occurred!");
    case kCFStreamEventEndEncountered:
        NSLog(@"A Read Stream Event End!");
    default:
        break;
}

The line UInt8 buf[BUFSIZE]; is causing the compiler to complain "Expected expression before UInt8" Why?

Thanks!

like image 993
Nick Avatar asked Mar 02 '11 05:03

Nick


1 Answers

Switch statements don't introduce new scopes. What's more, according to the C language spec, a regular statement must follow a case statement - a variable declaration is not allowed. You could put a ; before your variable declaration and the compiler would accept it, but the variable that you defined would be in the scope of the switch's parent, which means you cannot re-declare the variable inside another case statement.

Typically when one defines variables inside of case statements, one introduces a new scope for the case statement, as in

switch(event) {
    case kCFStreamEventHasBytesAvailable: {
        // do stuff here
        break;
    }
    case ...
}
like image 183
Lily Ballard Avatar answered Nov 12 '22 20:11

Lily Ballard