0

Why the code doesn't work unless I remove the comment?

#include <stdio.h>

int main(){
    int num = 5;
    switch(num){
        case 5:
            //printf("");
            int another = 1;
            printf("%d", num+another);
            break;
    }
}

gcc returns an error:

prog.c: In function ‘main’:
prog.c:7:13: error: a label can only be part of a statement and a declaration is not a statement

Thanks.

Marco
  • 61
  • 3

1 Answers1

1

The reason is outlined here: Why can't variables be declared in a switch statement?

As a workaround, you can do this:

#include <stdio.h>

int main(){
    int num = 5;
    switch(num){
        case 5:;
            //printf("");
            int another = 1;
            printf("%d", num+another);
            break;
    }
}

include a semicolon after the case as a workaround.Fool the compiler into thinking a statement follows and not a declaration. Taken from here

Community
  • 1
  • 1
Donal
  • 31,121
  • 10
  • 63
  • 72