C switch case 标签值已经出现

C switch case label value already appeared

为什么IDE认为有错误?

"case label value has already appeared in this switch at line 9 C/C++(1578)"

int main(int argc, char const *argv[])
{
    for (int i = 0; i < argc; i++)
    {
        switch (*argv[i])
        {
            case 'drow': printf("drow detected");
            break;
            case 'drows': printf("drows detected"); //line 9
            break;
            case 'rows': printf("rows detected"); //error at the first apostrophe '
            break;
            default: printf("Unknown arg, skipping.");
            break;
        }  
    }
    return 0;
}

您正在使用多字节字符常量作为标签

case 'drow':

其值是 int.

类型的实现定义

C 标准,6.4.4.4 字符常量。

The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

因此常量 'drow''drows' 似乎具有相同的整数值。

编译器可能会发出一条消息,指出常量 'drows' 对其类型而言太长。

另一方面,switch 语句中使用的表达式

switch (*argv[i])

不是多字节字符。所以在任何情况下 switch 语句都没有意义。

您可以使用 if-else 语句代替 switch 语句。例如

if ( strcmp( argv[i], "drow" ) == 0 )
{
    //...
}
else if ( strcmp( argv[i], "drows" ) == 0 )
{
    //...
}
else if ( strcmp( argv[i], "rows" ) == 0 )
{
    //...
}
else
{
    //...
}