I have already surfing the internet for the use of % in the line but I can't seem to get a proper answer.
-
1It's the modulus operator. A good answer : https://stackoverflow.com/a/17525046/6400614 – Rahul Bharadwaj May 22 '20 at 06:49
-
1% represents the mod function/operator, i.e it gives you the remainder of the division. In more daily speech, %2 checks if a number is odd or even. – visibleman May 22 '20 at 06:52
-
1Note that you can do the same thing with `player = (player % 2) + 1`. – Code-Apprentice May 22 '20 at 06:54
-
@Code-Apprentice That's not true. Should be `((player + 1) % 2) + 1` – amirali May 22 '20 at 07:05
-
@amirali It could be `player = 2 - player % 2` or `player = 2 - (player & 1)` to avoid division. – Blastfurnace May 22 '20 at 08:36
-
@amirali after further analysis, I think the formula in the title is incorrect. Or at least it doesn't do what I expected which was to toggle `player` between `1` and `2`. Instead `player` always retains the same value: `(1%2)?1:2 => 1` and `(2%2)?1:2 => 2`. So this formula is a noop if player only has the values 1 and 2. – Code-Apprentice May 22 '20 at 21:23
4 Answers
% means the remainder operator.
Here, player % 2
means the remainder after dividing variable player
by 2
. It will be a value less than 2 and greater than or equal to 0.
If value is 0, the ternary operator ?:
, evaluates to false and if value is 1, then ternary operator evaluates to true.
Therefore if value of player
is even, the player
will be set to 2
and if the value of the player is odd, then it will be set to 1
.

- 4,883
- 2
- 13
- 35
"%" is used to find the remainder. In your case, the value of the player will divide by 2 and it will give the remainder.

- 27
- 5
It is modulus operator i.e. calculates the remainder.
Let me break it and explain the whole expression:(assuming player
is of int type)
player = (player % 2) ? 1 : 2;
player % 2
means `get remainder by dividing player by 2
a?b:c
means if expression a ( note a is an expression) results to true or 1, then return b, else return c;
Now the whole inference:
If the remainder after dividing player
by 2 is 0, assign 1 to player
, else ( in which case remainder is 1), assign 2 to player
.

- 2,926
- 2
- 12
- 25
% Modulus Operator and remainder of after an integer division like 3%2=1 in your case it like
if(player%2==1){
player=1;
}else{
player=2;
}

- 514
- 5
- 11