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!
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 a switch-case statement? Yes. Enum can be checked. As an integer value is used in enum.
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.
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; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With