I have an unusual bug in my code, where sometimes, my code will return the wrong value. I have a ternary expression in a function which may be the culprit, and it's written like this;
corpusBoard[i][j] = (piece == 'o') ? 'o' : 'x';
Which should state, if piece
is equal to 'o', then assign 'o' to corpusBoard[i][j]
, otherwise assign 'x' to corpusBoard[i][j]
.
Are these two statements below equivalent? If not, why?
corpusBoard[i][j] = (piece == 'o') ? 'o' : 'x';
corpusBoard[i][j] = ((piece == 'o') ? 'o' : 'x');
Edit:
The particular issue I'm having is with a project I'm working on, where the system checks a database of sorts for matches, then instantiates player pieces to characters in the database. As the pieces can be either 'o' or 'x', I wanted a simple way to "flip" them when doing a pattern match in the database:
std::vector<std::vector<char>> Machine::matchCorpus(std::vector<std::vector<char>> corpusBoard)
{
for(int i = 0; i < corpusBoard.size(); i++){
for(int j = 0; j < corpusBoard[0].size(); j++){
if(corpusBoard[i][j] == 'M'){
corpusBoard[i][j] = ((piece == 'o') ? 'x' : 'o');
}
if(corpusBoard[i][j] == 'H'){
corpusBoard[i][j] = ((piece == 'o') ? 'o' : 'x');
}
}
}
return corpusBoard;
}
Unfortunately, in very rare cases, it returns the wrong value, even though if piece is 'o', and corpusBoard[i][j] == 'H'
, it should always assign corpusBoard[i][j]
to 'o', but rarely, it gets assigned 'x' instead.
Yes, they are equivalent. = comes last.