In a switch case statement, it says “duplicate case value” comes up as an error. Anyone know why?

后端 未结 5 821
余生分开走
余生分开走 2021-01-12 12:13

I am working on a rock paper scissors program, but this time the computer chooses rock half the time, scissors a third of the time, and paper only one sixth of the time. The

5条回答
  •  醉酒成梦
    2021-01-12 12:44

    The expression used in the switch statement must be integral type ( int, char and enum). In the Switch statement, all the matching case execute until a break statement is reached and Two case labels cannot have the same value.

    But in the above case with logical or condition. At first case: rock1 || rock2 || rock3: This will evaluate to 1 and second case scissors1 || scissors2: will also evaluate to 1. This is cause error as said Two case labels cannot have the same value.

    This is the reason compiler complains and giving an error:

    Compiler Error: duplicate case value

    To solve this convert to

    switch(computer) {
            case rock1: 
            case rock2:  
            case rock3:
                c = 1;
                break;
            case scissors1:
            case scissors2: //Now will not give any error here...
                c = 3;
                break;
            case paper:
                c = 2;
                break;
        }
    

提交回复
热议问题