Background of the problem:
A piece of code was written, as follows.
#include<stdio.h>
int main()
{
int a;switch (a) {
case 0:
break;
case 1:
int aa;
break;
case 2:
break;
default:
break;
}
return 0;
}
As shown above, an error will be reported when the code is compiled, with the error prompt “a label can only be part of statement and a declaration is not a statement”
cause of the problem:
It would not 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”。
Before C99, all definitions in a code block must be before declaration. Therefore, a label is meaningless before definition. C99 relaxed this restriction, allowing mixed definitions and declarations in code blocks, but the label cannot be changed before the definition
solution:
#include<stdio.h>
int main()
{
int a;
switch (a) {
case 0:
break;
case 1:; //Add an empty ';' to mark the empty statement
int aa;
break;
case 2:
break;
default:
break;
}
return 0;
}
#include<stdio.h>
int main()
{
int a;
int aa; //Definition before switch
switch (a) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
return 0;
}
Read More: https://stackoverflow.com/questions/18496282/why-do-i-get-a-label-can-only-be-part-of-a-statement-and-a-declaration-is-not-a
Similar Posts:
- Vue Switch JS ERROR:unexpected lexical declaration in case block
- [Solved] Lexical declaration cannot appear in a single-statement context
- C Compilation Error: implicit declaration of function xxx is invalid in C99 [-Wimplicit-function-declaration]
- [swscaler @ …] deprecated pixel format used, make sure you did set range correctly
- [Solved] error C2275: ‘TOKEN’ : illegal use of this type as an expression
- Makefile:xxx: recipe for target ‘xxx’ failed
- C write and read file via FILE and open method in a+ or r mode
- malloc: *** error for object pointer being freed [How to Solve]
- The solution of “no matching function for call to…” in G + + compilation
- [Solved] VS winsock.h and ws2def.h a large number of redefined error