Home > Back-end >  "error: duplicate case value" error when using goto in switch statement
"error: duplicate case value" error when using goto in switch statement

Time:11-12

I was trying to use the goto statement to travel between different switch-cases. I understand, it's not preferable to use goto as it would make the program tough to understand, but I really need it.

Here's the example version of my code:

switch(something){
    case "c1":
        //some code
        break;
    case "c2":
       //some code
       break;
    case "c3":
        if(condition1)
            goto case "c1";
        if(condition2)
            goto case "c2";
    default:
        break;
}

Now, when I run the code, I get the following error error: duplicate case value which applies to both goto case "c1" and goto case "c2".

I'm not sure why the compiler is thinking the goto on a switch-case is redefining another case in the switch statement with the same condition and hence throwing that duplicate error. Any help and reasons for this error is appreciated.

Thanks!

CodePudding user response:

In any case the switch statement does not make a sense because you are using string literals as case labels.

switch(something){
    case "c1":
        //some code
        break;
    case "c2":
       //some code
       break;
    case "c3":
        if(condition1)
            goto case "c1";
        if(condition2)
            goto case "c2";
    default:
        break;
}

The expression in the switch statement is converted to an integral or enumeration type that can not be implicitly converted to pointers or string literals.

Maybe you need to use character literals as for example

case 'c1':

The second problem is you may not use case labels with goto statements. You may use with the goto statements only labels that are presented as identifiers. The syntax of the goto statement is

goto identifier ;

So the compiler thinks that the case labels used in goto statements redefine already introduced case labels.

  • Related