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

后端 未结 5 716
余生分开走
余生分开走 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:45

    You can't use || in case branches. Sorry :(
    When you use || it does a logical or on them, that says "is rock1 or rock2 or rock3 not a zero?". And the answer is yes, at least one of those is not zero. So rock1 || rock2 || rock3 is true, which is 1. And scissors1 || scissors is also true, which is 1. So you have two case branches for the 1 case.

    You should simply use case fallthrough to select multiple conditions:

    switch(computer) {
        case rock1: case rock2: case rock3:
            c = 1;
            break;
        case scissors1: case scissors2:
            c = 3;
            break;
        case paper:
            c = 2;
            break;
        default:
            std::cerr << "INVALID COMPUTER MOVE";
    }
    

    Also, I always have a default in my case switches. Sometimes mistakes happen, and we definitely want to know if it doesn't hit any of the case branches. I'm also pretty paranoid about missing else statements, but about half the time it's ok if there's no else.

提交回复
热议问题