Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"error: duplicate case value" error when using goto in switch statement

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading