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

在这里我没有得到所需的输出
谁能解释一下为什么?

我的预期输出是:2,2

最佳答案

在 switch 语句中(在 C 中),您不能在 case 中使用变量。您必须使用常量。

而且,case 'x': 不是指变量 x 而是指一个字符常量 'x'。您不是在测试您似乎想要的内容...在这种情况下,您正在测试 case 121: ,其中 121 是字母“x”的 ascii 代码。

您可以使用以下方法解决您的问题:

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

关于c - 在 switch case 语句中使用变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17580985/

10-11 23:07
查看更多