在使用switch时在case 后面申请变量会出现 error: a declaration cannot have a label 的提示
原因:Case statements are only ‘labels’. This means the compiler will interpret this as a jump directly to the label.The problem here is one of scope. Your curly brackets define the scope as everything inside the ‘switch’ statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it.
解决方法:在case 后面加一个{ }做相应的操作。
如下:
case STAT1:
{ //双括号解除warning
uint16_t Temp; //声明变量
if (XXXXX) ;
break;
}
case STAT2:
本文探讨了在switch-case结构中直接声明变量导致的编译错误,并提供了有效的解决方案。通过在case后面添加一对大括号来创建局部作用域,可以在不触发警告的情况下正确声明和初始化变量。
1万+

被折叠的 条评论
为什么被折叠?



