I want to know, with unsigned int a;
, if while(a-- != 0)
and while(a-- > 0)
will take same time and number of instructions to execute or not.
Which one is better to use?
I want to know, with unsigned int a;
, if while(a-- != 0)
and while(a-- > 0)
will take same time and number of instructions to execute or not.
Which one is better to use?
The concept of "faster" or "slower" is not applicable to C code. C language constructs do not have any specific "speed" associated with them. Only the resultant machine code can be analyzed for speed.
If a
is of unsigned type, any self-respecting compiler should generate identical code for both versions. "Greater than zero" and "not equal to zero" are equivalent comparisons for unsigned values.
Even if some compiler decides to translate it literally, for many modern platforms the difference would be just one specific conditional jump instruction. The performance would be the same anyway.
They both take the same time and for unsigned int a
will probably generate the same code anyway.
Regarding the second question, I would favor the second:
while(a-- > 0)
For 2 reasons:
a
will go down from the initial value to 0
inclusive.signed
and unsigned
values. You can use this idiom for all downward iterations, the loop will be skipped correctly if a
is signed
and has a negative initial value.