0

The following code uses a switch with enum. The main program passes the argument correctly to the function, but the correct switch line is not executed. Can you advise why it is not entering the switch conditions?

enum MyEnum { Enum1 = 1, Enum2 = 0x0D }; bool compute(MyEnum code) { switch(code) { Enum1: return true; Enum2: return false; }; cout << "why here??" << endl; // this line is getting printed for both inputs return false; } int main() { cout << "compack=" << compute((MyEnum)1) << endl; // printed "0" cout << "compack=" << compute((MyEnum)13) << endl; // printed "0" } 

I checked the other questions related to switch and enum (eg 3019153), but cant figure out the bug.

0

5 Answers 5

6

You are missing the case keyword:

switch(code) { case Enum1: return true; case Enum2: return false; }; 
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, and the compiler did not even complain? Thanks very much.
@R71 It might not be complaining because of two factors: First: foo: is simply a label (you could use goto foo; to jump to this label, for example.) Second: You are probably not using -Wall flag (it shows some useful warnings): ` ▶ g++ -Wall switch.cpp -o 1 switch.cpp: In function ‘int main()’: switch.cpp:7:9: warning: label ‘foo’ defined but not used [-Wunused-label] foo: return 1; ^ `
1
switch(code) { case Enum1: return true; case Enum2: return false; }; 

Comments

1

You forgot to write case

switch(code) { case Enum1: return true; case Enum2: return false; }; 

A generic switch is like:

switch(var) { case val1: foo(); break; case val2: bar(); break; default: error(); }; 

Comments

0

You forgot case there..

switch(code) { case Enum1: //do something break; case Enum2: //do something break; }; 

Comments

0

Okay, so others have answered that you are missing the case keyword. What hasn't been explained, though, is why the original code compiled. That's because without the case keyword, it was treated as a goto label. In fact, this compiles:

switch (i) { if (j == 3) { case 1:; L1:; } else { goto L1; case 2:; } } 

Note that the j==3 is actually dead code. It can never be executed. For an actual useful application of this, see Duff's device. By the way, compiling with full warnings enabled would have warned you about an unused goto label, at least with g++ and clang++ (-Wall -Wextra -pedantic).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.