在switch中的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;
我在case:break中声明了变量,结果gcc编译时就提示:
error: a label can only be part of a statement and a declaration is not a statement
有下面三种方法处理:
1、将变量定义放到case:break外面;
2、将case:break中间的语句用{}包含;
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后{}括号
3、在“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;