简体   繁体   中英

Modulo in conditional ternary operator

In C++, someone wrote the following:

player = (player % 2) ? 1 : 2;

From what I've read, the variable 'player' will evaluate to 1 if the condition inside the parantheses is true, but this doesn't seem like a condition which can either be true or false.

If player is an int or has in implicit conversion to int , then the modulo operation will either return 0 or 1 in this case for even or odd respectively.

From there, int has an implicit conversion to bool such that 0 evaluates to false and all non-zero values (including negative values) evaluate to true .

Example
Starting with

player = 2;

We can follow the ternary expression step-by-step

player = (player % 2) ? 1 : 2;
player = (2 % 2) ? 1 : 2;
player = 0 ? 1 : 2;  // 0 evaluates to false
player = 2;

However, I think this logic is flawed, they probably meant

player = (player % 2) ? 2 : 1;

This will indeed "switch" the players in an alternating fashion, meaning when player is initially 1 , after the ternary it will be assigned 2 and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM