Reputation: 753
# include <stdio.h>
int main(void)
{
int var=1, x=1, y=2;
switch(var)
{
case 'x':
x++;
break;
case 'y':
y++;
break;
}
printf("%d %d",x,y);
return 0;
}
here I am not getting the required output Can anyone explain it why ?
My Expected output is : 2,2
Upvotes: 3
Views: 12189
Reputation: 753805
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
Upvotes: 8
Reputation: 3974
using 'x' in quotes is actually using the constant ASCII code value for the character x, which is actually number value 120 (according to the ASCII chart). It does not use the variable you declared.
Upvotes: 2
Reputation: 14510
In a switch statement (in C), you can't use variables in case
. You must use constant.
And also, case 'x':
do not refer to the variable x
but to a constant 'x'
who is a char. You are not testing what you seem to want... In this case, you are testing case 121:
, where 121 is the ascii code for the letter 'x'.
You can solve your problem with something like :
# include <stdio.h>
#define INIT_X 1
#define INIT_Y 2
// ^^^^^^^^^^^^^
int main(void)
{
int var=1, x=INIT_X, y=INIT_Y;
// ^^^^^^^^^^^^^^^^^^
switch(var)
{
case INIT_X:
// ^^^^^^
x++;
break;
case INIT_Y:
// ^^^^^^
y++;
break;
}
printf("%d %d",x,y);
return 0;
}
Upvotes: 10
Reputation: 5817
You cannot use variables in a case
as the values must be compile-time constants. Also your code is incorrect as 'x'
and 'y'
are constants (literals), and hence do not refer to the variables x
and y
.
Upvotes: 2