9

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!

Nick
  • 19,198
  • 51
  • 185
  • 312
  • 2
    It's described [here](http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement) in detail. – Nikita Rybak Mar 02 '11 at 05:19
  • 1
    This has been asked many, many times before: http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement http://stackoverflow.com/questions/1231198/declaring-variables-inside-a-switch-statement http://stackoverflow.com/questions/1115304/can-i-declare-variables-inside-an-objective-c-switch-statement http://stackoverflow.com/questions/1180550/weird-switch-error-in-obj-c http://stackoverflow.com/questions/3757445/switch-case-declaration-with-initialization-declaration-and-then-assignment – Adam Rosenfield Mar 02 '11 at 06:21

1 Answers1

18

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 ...
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347