3

Is this a normal error that will happen with just a blank method? I used a custom Makefile btw.

case MODE: //mode is just an enum stackoverflow

  printf("");

  char temp = '5';

CSftp.c:335:9: error: expected expression char temp = '5';

deleting printf(""); causes the error to appear. Or is this a sympton from a problem far away.

4 Answers4

7

Variables should not be declared in a case without being correctly scoped by an enclosing {..} block. A good explanation can be found here. Declare char temp before the switch statement or enclose the code for the case.

Option 1:

char temp; 
switch(condition){
    ...
    case MODE:
        temp = '5';
        ...
}

Option 2:

switch(condition){
    ...
    case MODE:
    {
        char temp = '5';
        ...
    }
    case NEXT:
        ...
}
RadioSilence
  • 348
  • 1
  • 10
7

GCC 9.3 has a more easily understandable error message:

a label can only be part of a statement and a declaration is not a statement

That is, C’s syntax simply forbids this because a case label needs to be attached to a syntactic statement, and declarations in C aren’t statements. But compound statements are statements, which is why surrounding the whole thing by {…} works.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

if you want to declare variable in the case add the block there:

switch(x)
{
    case MODE: //mode is just an enum stackoverflow
    {
        printf("");   

        char temp = '5';
    }
}
0___________
  • 60,014
  • 4
  • 34
  • 74
1

you can only assign a value to a variable in case unless you use a block

    case MODE: 
    {
        printf("");   

        char temp = '5';
    }

but note that you only have this variable in this statement after you exit the block variable temp is no longer visible.

hanie
  • 1,863
  • 3
  • 9
  • 19