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 way I did this was I enumerated six possible computer choice values:
enum choicec {rock1, rock2, rock3, scissors1, scissors2, paper};
choicec computer;
But then, after the computer makes its choice, I have to convert these enumerated values to either rock, paper, or scissors. I did this using a switch-case statement:
switch(computer) {
case rock1 || rock2 || rock3:
c = 1;
break;
case scissors1 || scissors2: //ERROR!
c = 3;
break;
case paper:
c = 2;
break;
}
one is rock, two is paper, and three is scissors. However, on the line where I have error written in as a comment, it gives me this error: [Error] duplicate case value.
I'm not sure why. Any ideas?
I am not sure what you doing, but switch statement should look like this
Change it to:
rock1 || rock2 || rock3
andscissors1 || scissors2
are both expressions which evaluate to "true", hence the conflict.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 secondcase 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
That
switch
statement does not do what you think.Each
case
defines one value that the value ofcomputer
is matched against. Combining several values with logical disjunction to give the value associated with a singlecase
label does not make the corresponding block be entered when the value ofcomputer
is equal to any of those values, but rather when it is equal to the result of their logical OR combination. Not very meaningful, indeed.This is how you could rewrite your
switch
statement in order to make more sense:You can't use
||
incase
branches. Sorry :(When you use
||
it does a logical or on them, that says "isrock1
orrock2
orrock3
not a zero?". And the answer is yes, at least one of those is not zero. Sorock1 || rock2 || rock3
istrue
, which is1
. Andscissors1 || scissors
is alsotrue
, which is1
. So you have twocase
branches for the1
case.You should simply use
case
fallthrough to select multiple conditions: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 noelse
.