0

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;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Ali Amjad
  • 11
  • 1
  • 2
  • The line `(player % 2) ? 1 : 2` basically evaluates if `(player % 2)` is true. If it's true, the `1` is selected, otherwise, if it's false, the `2` is selected. The selected value is then assigned to `player`. – PerryC Jan 13 '16 at 18:20

4 Answers4

3

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.

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
3

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.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
0

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.

Frecklefoot
  • 1,660
  • 2
  • 21
  • 52
0

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;
}