1

I'm a newbie in C++. As fas as I know, something like

switch(ival)
{
    case 1,2,3:
    /* do something */
    /* other case selections */
}

is wrong. The correct way is to write:

switch(ival)
{
    case 1: case 2: case 3: // in multiple lines if you prefer
    /* do something */
    /* other case selections */
}

That said (hoping it's correct), what happens when you compile the first? Visual Studio intellisense detects an error, but the program compiles fine.

I experimented a bit and I was betting that he would execute "do something" if ival was 1, but not if it was 2 or 3. I've setup multiple case statement like that, everyone with its own control variable to keep track of the execution, but nothing seems to happen as they all keep initialization values through the end of the program.

I'm puzzled. Anyone knows what happens behind the curtain?

Andrea Bocco
  • 792
  • 5
  • 14

1 Answers1

3

When the compiler sees a case statement case N it will always interpret N as an integer. In this case, your compiler is evaluating the expression 1,2,3 as 3. Your /* do something */ code is only executed when ival is 3. (Tested with MSVS2015).

As you noted, this expression isn't the right way to express that you want multiple cases to be handled by the same code, and you should expect other compilers to handle the situation differently.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39