简体   繁体   中英

Swap a pointer between two objects

I have three pointers, *player1 , *player2 and *currentPlayer .

The pointer *currentPlayer will always be pointing to either *player1 or *player2 . To switch between the two, I've been doing the following:

if (currentPlayer == player1) {
        currentPlayer = player2;
}
else {
    currentPlayer = player1;
}

My question is, is there a simpler, more elegant way to swap between these two pointers?

No, conceptually there's no simpler way.

Syntactically the ternary operator is a little shorter:

currentPlayer = currentPlayer == player1 ? player2 : player1;

如果使用数组,这也可以工作:

currentPlayer = playerArray + (currentPlayer - playerArray ^ 1);

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