在switch中的case語句中聲明變量編譯的問題函數
先來看段代碼,別管什麼意思:spa
case 10: int i = 0, j = 0; for (i = 0; i < 11; i++) recive_phone[i] = msgbuf.text[i]; recive_phone[i] = '\0'; printf("%s文件%s函數%d行:接收端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, recive_phone); for (j = 0; msgbuf.text[i] != '\0' && j < 12; i++,j++) center_phone[j] = msgbuf.text[i]; center_phone[j] = '\0'; printf("%s文件%s函數%d行:發送端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, center_phone); break;
我在case:break中聲明瞭變量,結果gcc編譯時就提示:code
error: a label can only be part of a statement and a declaration is not a statementblog
有下面三種方法處理:ci
一、將變量定義放到case:break外面;it
二、將case:break中間的語句用{}包含;io
case 10: { int i = 0, j = 0; for (i = 0; i < 11; i++) recive_phone[i] = msgbuf.text[i]; recive_phone[i] = '\0'; printf("%s文件%s函數%d行:接收端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, recive_phone); for (j = 0; msgbuf.text[i] != '\0' && j < 12; i++,j++) center_phone[j] = msgbuf.text[i]; center_phone[j] = '\0'; printf("%s文件%s函數%d行:發送端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, center_phone); } break;
注意case後{}括號編譯
三、在「case:」後面加「;」處理。class
case 10: ; int i = 0, j = 0; for (i = 0; i < 11; i++) recive_phone[i] = msgbuf.text[i]; recive_phone[i] = '\0'; printf("%s文件%s函數%d行:接收端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, recive_phone); for (j = 0; msgbuf.text[i] != '\0' && j < 12; i++,j++) center_phone[j] = msgbuf.text[i]; center_phone[j] = '\0'; printf("%s文件%s函數%d行:發送端號碼:%s\n", __FILE__ , __FUNCTION__, __LINE__, center_phone); break;