2011-03-02 56 views
6

我在這個代碼塊得到一個編譯錯誤:預計表達之前......在switch語句

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; 
} 

UInt8 buf[BUFSIZE];導致編譯器抱怨「UINT8之前預期的表達」爲什麼?

謝謝!

+2

它描述這裏](http://stackoverflow.com/questions/92396/ why-cant-variables-be-decla-in-a-switch-statement)。 – 2011-03-02 05:19:30

+1

這已被問了很多很多次: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 /奇怪開關錯誤在obj-c http://stackoverflow.com/questions/3757445/switch-case-declaration-with-initialization-declaration-and-then-assignment – 2011-03-02 06:21:54

回答

16

Switch語句不會引入新的作用域。而且,根據C語言規範,正則語句必須遵循一個case語句 - 不允許使用變量聲明。你可以在你的變量聲明之前放置一個;,編譯器會接受它,但是你定義的變量將在switch的父級範圍內,這意味着你不能在另一個case語句中重新聲明該變量。

通常,當一個限定case語句的內部變量,一個引入了對case語句一個新的範圍,如在

switch(event) { 
    case kCFStreamEventHasBytesAvailable: { 
     // do stuff here 
     break; 
    } 
    case ... 
} 
+0

真棒解釋。謝謝! – Nick 2011-03-02 05:21:08