You misunderstand the switch
statement.
The switch statement compares the expression (often a simple variable) in the switch (expression)
with a series of distinct compile-time constant values in the various case
labels, and executes the code after that label. If the value does not match any of the explicit case
labels, then the default
label is used if it is present, or the whole switch
is skipped if there is no default
label.
In your code, you have var
set to 1
. Neither case 'x':
nor case 'y':
matches 1
(they'd be equivalent to case 120:
and case 121:
in most codesets based on ASCII), and there is no default
, so the switch
is skipped, and the output is 1 2
(not, as you appear to have expected, 2 2
).
What is a compile-time constant?
The values in the case labels must be determinable by the compiler as the code is compiled, and must be constant expressions. That means that the expressions in the case labels cannot refer to variables or functions, but they can use basic computations on fixed (integral) values.
Given:
#include <math.h>
const int x = 3; // C++ compilers treat this differently
enum { BIG_TIME = 60 };
#define HOURS(x) (3600 * (x))
case sin(x): // Invalid - function of a variable
case x: // Invalid - variable
case sin(0.0): // Invalid - function
case 'x': // Valid - character constant
case 'xy': // Valid but not portable
case BIG_TIME: // Valid - enumeration value names are constant
case HOURS(2): // Valid - expands to (3600 * (2)) which is all constant