Using variable for switch case statement

c

Solution

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;
}

Problem

``` # 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

Original source

Related problems