在switch中的case語句中聲明變量編譯的問題ide
先來看段代碼,別管什麼意思:函數
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編譯時就提示:spa
error: a label can only be part of a statement and a declaration is not a statementcode
有下面三種方法處理:blog
一、將變量定義放到case:break外面;ci
二、將case:break中間的語句用{}包含;it
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後{}括號io
三、在「case:」後面加「;」處理。編譯
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;