Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum type in a switch statement

Tags:

I am using a switch statement to return from my main function early if some special case is detected. The special cases are encoded using an enum type, as shown below.

typedef enum {     NEG_INF,     ZERO,     POS_INF,     NOT_SPECIAL } extrema;  int main(){      // ...      extrema check = POS_INF;      switch(check){         NEG_INF: printf("neg inf"); return 1;         ZERO: printf("zero"); return 2;         POS_INF: printf("pos inf"); return 3;         default: printf("not special"); break;     }      // ...      return 0;  } 

Strangely enough, when I run this, the string not special is printed to the console and the rest of the main function carries on with execution.

How can I get the switch statement to function properly here? Thanks!

like image 512
tomocafe Avatar asked Mar 06 '13 02:03

tomocafe


People also ask

Can we use enum in switch?

We can use Enum in Switch case statement in Java like int primitive. Below are some examples to show working of Enum with Switch statement.

Can enum be checked in switch-case statement?

Can enum be checked in a switch-case statement? Yes. Enum can be checked. As an integer value is used in enum.

Can enum type can be passed as an argument to switch statement?

Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum.


2 Answers

No case labels. You've got goto labels now. Try:

switch(check){     case NEG_INF: printf("neg inf"); return 1;     case ZERO: printf("zero"); return 2;     case POS_INF: printf("pos inf"); return 3;     default: printf("not special"); break; } 
like image 114
ldav1s Avatar answered Sep 21 '22 03:09

ldav1s


You haven't used the keyword "case". The version given below will work fine.

typedef enum {     NEG_INF,     ZERO,     POS_INF,     NOT_SPECIAL  } extrema;  int main(){      extrema check = POS_INF;      switch(check){         case NEG_INF: printf("neg inf"); return 1;         case ZERO: printf("zero"); return 2;         case POS_INF: printf("pos inf"); return 3;         default: printf("not special"); break;     }      return 0;  } 
like image 23
Deepu Avatar answered Sep 23 '22 03:09

Deepu