ShiftyCodes ShiftyCodes - 3 months ago 20
C++ Question

C++ int comparison efficiency

Is there any difference in the performance of the following code snippets? Which one performs best and why?

int i = 1000000000;

while(i != 0) { i--; }


or

int i = 1000000000;

while(i) { i--; }


or

int i = 1000000000;

while(i > 0) { i--; }


I see a lot of people use the first example and wonder why. Easier to read?

Answer

Is there any difference in the performance of the following code snippets?

No.

First two are equivalent, and all three can be optimized to exactly same assembly.

I see a lot of people use the first example and wonder why. Easier to read?

It requires the reader to know fewer language rules than the second one. In particular, the second program requires the knowledge that conditional expression is converted to bool, and that the conversion from int has the same result as inequality with zero.

Note that if i were replaced with a floating point number, or if the decrement were modified to have more complexity (for example: decrement by 2), then the third option would be easiest to prove correct. With integers and single decrement, there is no difference.