C中带有OR的Switch语句

我正在尝试使用带有“OR”的 switch 语句。

我经常在 Shell 脚本中使用这种方法,但是在 C 编程中尝试时它不起作用。

C 中的示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char *str = "azen";

    int len = strlen(str);
    char c = str[len - 2];
    
    switch (c)
    {
    case 'a' || 'e' || 'i' | 'y' || 'u' || 'o':
        printf("1");
        break;
    default:
        printf("2");
    }

    return 0;
}

执行

2

这不应该工作吗?

回答

您在代码中的情况无法执行正确的计算,因为

case 'a' || 'e' || 'i' | 'y' || 'u' || 'o':
    ...

每次都被评估为case 1(或者我们可以说case true),因为这些字符的所有 ASCII 值都是大于 1 的值。

你可以case一个接一个地修复它:

case 'a':
case 'e':
case 'i': 
case 'y':
case 'u': 
case 'o':
    ...


以上是C中带有OR的Switch语句的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>