参考资料:
https://*.com/questions/18496282/why-do-i-get-a-label-can-only-be-part-of-a-statement-and-a-declaration-is-not-a
问题背景:
写了一段code,如下:
#include<stdio.h> int main()
{
int a;switch (a) {
case :
break;
case :
int aa;
break;
case :
break;
default:
break;
} return ;
}
如上所示code编译时候会报错,错误提示“a label can only be part of statement and a declaratioin is not a statement”。
问题原因:
引用一段话解释为“Prior to C99, all declarations had to precede all statements within a block, so it wouldn't have made sense to have a label on a declaration. C99 relaxed that restriction, permitting declarations and statement to be mixed within a block, but the syntax of a labeled-statement was not changed. – Keith Thompson”。
翻译过来就是,C99之前,在一代码块中所有的定义都必须在声明之前,所以,一个标签在定义之前是没有意义的。C99放宽了这个限制,允许代码块中混合定义、声明,但这这个标签不能在定义之前的限制没有改变。
解决方法:
#include<stdio.h> int main()
{
int a;
switch (a) {
case :
break;
case :; //加一个空的‘;’,标示空声明
int aa;
break;
case :
break;
default:
break;
} return ;
}
#include<stdio.h> int main()
{
int a;
int aa; //定义放到 switch 之前
switch (a) {
case :
break;
case :
break;
case :
break;
default:
break;
} return ;
}