Should I use the ++ operator on temporary inline variables?

Viewed 91

I was wondering about this pre-mature and not-too-important thing. I have written:

m_playerIndex = ++m_playerIndex % 2 // always either 0 or 1 (int)

for my chess game to make sure the other player will do the next move after the move that just has been done. However it's not quite readable, is it?

On top of that, it's incrementing a variable by 1, then calling the module operator of 2 on the adapted variable, meaning I have this temporary variable, which I assign to m_playerIndex and immediately after have it replaced by the result of %2. What would be the most efficient? Is it option 2, 1, or is there no difference at all? (I don't have programs to check those things yet.)

1)

m_playerIndex = ++m_playerIndex % 2

2)

m_playerIndex = (m_playerIndex + 1) % 2
2 Answers

The expression

m_playerIndex = (m_playerIndex + 1) % 2

clearly communicates to the reader what is going on. Every slightly possible optimization here is the compiler's job.

Apart from that, for your curiosity, check out https://godbolt.org/ where you can see and compare the assembler instructions created for your code.

You have bigger problems than readability or performance - the behavior of the expression is undefined.

You’re attempting to update m_playerIndex more than once without an intervening sequence point, through both the ++ and = operators. That’s not guaranteed to do what you expect.

In order for the expression to be well-defined, it needs to be written as

m_playerIndex = (m_playerIndex + 1) % 2;

It’s not clear to me why you think you need to increment the variable in addition to this, since the result will only ever be 0 or 1.

Related