I know that this code does not work as "expected". Just looking quickly at this code, we think the return value should be 1, but in the execution it returns returns 3.
// incorrect
variable = 1;
switch (variable)
{
case 1, 2:
return 1;
case 3, 4:
return 2;
default:
return 3;
}
and there are some correct options to do this:
// correct 1
variable = 1;
switch (variable)
{
case 1: case 2:
return 1;
case 3: case 4:
return 2;
default:
return 3;
}
or
// correct 2
switch (variable)
{
case 1:
case 2:
return 1;
case 3:
case 4:
return 2;
default:
return 3;
}
This is partially answered in Multiple Cases in Switch:
I would like to know why the incorrect form does compile without error or even warnings (at least in the Borland C++ compiler).
What does the compiler understand in that code?