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:
REDbeing the first item in an enum list, equals value0. Socase RED:will never get called when you doint x=1; switch(x)GREEN:in the first example is a uselessgotolabel which fills no purpose.case GREEN:in the second example checks for value 1 andxis indeed 1 so thecase GREEN:gets executed. Thecase RED:above it is irrelevant.
