使用变量用于switch case语句

Ama*_*ngh 2 c

# 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;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我没有得到所需的输出任何人都可以解释为什么?

我的预期输出是:2,2

Pie*_*aud 9

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

而且,case 'x':不要引用变量,x而是引用一个常量'x'为char 的变量.你没有测试你想要的东西......在这种情况下,你正在测试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;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 8

你误解了这个switch说法.

switch语句将表达式(通常是一个简单变量)switch (expression)与各种case标签中的一系列不同的编译时常量值进行比较,并在该标签之后执行代码.如果该值与任何显式case标签都不匹配,则使用default标签(如果存在),或者switch如果没有default标签则跳过整个标签.

在您的代码中,您已var设置为1.既不匹配case 'x':也不case 'y':匹配1(它们相当于case 120:case 121:大多数基于ASCII的代码集),并且没有default,所以switch跳过,输出1 2(不是,你似乎预期的那样2 2).

什么是编译时常量?

案例标签中的值必须由编译器在编译代码时确定,并且必须是常量表达式.这意味着case标签中的表达式不能引用变量或函数,但它们可以对固定(整数)值使用基本计算.

鉴于:

#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
Run Code Online (Sandbox Code Playgroud)

  • 即使某些编译器接受它,它也不会是C有效表达式. (2认同)