. Advertisement .
..3..
. Advertisement .
..4..
I don’t know what I’m doing wrong, but I’ve already lost a couple of days struggling with this. Here is my command line:
#include<stdio.h>
int main() {
char option = 'a';
switch (option)
{
case 'a':
char * str = "Case 'a' hit.";
printf("%s", str);
break;
}
}
This returns:
a label can only be part of a statement and a declaration is not a statement
I don’t have any experience with a label can only be part of a statement and a declaration is not a statement. In this case, how should I change?
The cause: The error occurs when using switch statement in C, because the language treats cases similar to labels.
Solution: After the case ‘a’ statement on line 7 needs to add a semi-colon. Alternatively, the entire case can be enclosed in curly braces to circumvent the error.
This is a peculiarity of C grammar. This is a quirk of the C grammar. A label cannot appear immediately prior to a declaration, such as
char *str ...;
. It can only appear before a assertion (printf(...);
). This was not a problem in C89 because declarations could only be placed at the beginning of a block. You could move the label down to avoid this issue. C99 allows you to mix code and declarations, but you cannot place a label directly before a declaration.To make the label empty, you can place a semicolon after Renan’s colon. This is what I would do with machine-generated code. You can also raise the declaration up to the top of your function.