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.

Community
  • 1
  • 1
R71
  • 4,283
  • 7
  • 32
  • 60

5 Answers5

6

You are missing the case keyword:

switch(code) {
 case Enum1:  return true;
 case Enum2:  return false;
};
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Wow, and the compiler did not even complain? Thanks very much. – R71 May 05 '14 at 05:05
  • @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; ^ ` – Leonardo Lourenço Jul 31 '17 at 04:38
1
switch(code) 
{
     case Enum1:  return true;
     case Enum2:  return false;
};
tim
  • 121
  • 4
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();
};
0

You forgot case there..

switch(code)
 {
  case Enum1: 
             //do something  
             break;
  case Enum2:
            //do something 
             break;
 };
Deva
  • 48
  • 6
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).

kec
  • 2,099
  • 11
  • 17