Momoos
Momoos

Reputation: 27

C switch case label value already appeared

Why IDE thinks there is an error ?

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

Upvotes: 1

Views: 1733

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

You are using a multibyte character constant as a label

case 'drow':

Its value is implementation defined of the type int.

The C Standard, 6.4.4.4 Character constants.

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.

So it seems the constants 'drow' and 'drows' have the same integer value.

The compiler could issue a message that the constant 'drows' is too long for its type.

On the other hand, the expression used in the switch statement

switch (*argv[i])

is not a multibyte character. So in any case the switch statement does not make a sense.

Instead of the switch statement you could use if-else statements. For example

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

Upvotes: 1

Related Questions