I can`t understand this line why we use question mark "?" in it. there are 2 player 1 and 2 .
player = (player % 2) ? 1 : 2;
I can`t understand this line why we use question mark "?" in it. there are 2 player 1 and 2 .
player = (player % 2) ? 1 : 2;
It's the ternary operator.
This line of code will set player
to 1
if player
originally was odd, and to 2
if it was even.
This is a conditional if
, and is the same as:
if(player % 2)
player = 1; // Odd
else
player = 2; // Even
Another way to do this without an if
branch:
player = 2 - (player & 0x01);
The least significant bit is zero for even numbers.
It's the ternary operator. It takes this form:
boolean expression ? a : b;
Which translates to:
If this expression is true, then a else b
It's often used as the right-hand expression in assignment operators. In your case player
is being assigned 1 or 2 based on whether they are even or odd.
It meaning that if the Condition is true so Player have the Value 1 else it have 2.
if(player % 2) {
player = 1;
} else {
player = 2;
}