Home > Software design >  Case statement label in C
Case statement label in C

Time:02-05

My below code doesn't print Hi, instead it runs and prints Bye

#include <stdio.h>

typedef enum 
{ 
    RED, 
    GREEN, 
    BLUE 
} color;

int main(void) {
    color chosenColor = GREEN;
    printf("val %d\n",chosenColor);
    int x=1;
    switch(x)
    {
        case RED:
        GREEN:
        printf("HI");
        break;

        default:
        printf("BYE");
        break;
    }
    return 0;
}


Output val 1 BYE

But if I modify it as below and add case in front of GREEN, it prints Hi

#include <stdio.h>

typedef enum 
{ 
    RED, 
    GREEN, 
    BLUE 
} color;

int main(void) {
    color chosenColor = GREEN;
    printf("val %d\n",chosenColor);
    int x=1;
    switch(x)
    {
        case RED:
        case GREEN:
        printf("HI");
        break;

        default:
        printf("BYE");
        break;
    }
    return 0;
}

Output val 1 HI

Can someone tell why is this even happening in first program, is something wrong there?

CodePudding user response:

GREEN: without case does not form a case-labeled statement for switch. It declares GREEN to be a label for goto statement. It has no effect on the switch.

Turning up warnings in your compiler might produce a warning message that the label is not used. Generally, you should request lots of warnings and elevate warnings to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /Wx.

CodePudding user response:

  • RED being the first item in an enum list, equals value 0. So case RED: will never get called when you do int x=1; switch(x)
  • GREEN: in the first example is a useless goto label which fills no purpose.
  • case GREEN: in the second example checks for value 1 and x is indeed 1 so the case GREEN: gets executed. The case RED: above it is irrelevant.
  •  Tags:  
  • Related