在switch中的case语句中声明变量编译出错的解决方案

本文探讨了在C语言的switch-case结构中声明变量时遇到的编译错误,并提供了三种解决方案,包括将变量声明移至外部、使用花括号包裹case块以及在case后添加分号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://my.oschina.net/u/124452/blog/175772

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值