-12

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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 5
    Compile and disassemble and investigate the output. The C standard doesn't say anything about the number of instructions, so it depends on the compiler, etc. – cadaniluk Oct 30 '15 at 20:14
  • 1
    You could also use `while(a--)` – Linus Oct 30 '15 at 20:14
  • 2
    Best would be to use the [arrow operator](http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator): `while (a --> 0)`... – cadaniluk Oct 30 '15 at 20:16
  • @AnT, the question specifies uint. – Charles Duffy Oct 30 '15 at 20:18
  • 1
    ...but, yeah. Could in theory depend on the compiler and the instruction set, but in practice, neither will be faster (and someone focusing on this kind of microoptimization is ignoring the structural areas of their code which they *should* be paying attention to instead). – Charles Duffy Oct 30 '15 at 20:19
  • At least some versions of gcc [output the same thing](https://goo.gl/Rd7zYD). – artless noise Nov 01 '15 at 16:04

2 Answers2

2

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

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:

  • it is more readable: it makes it obvious to the reader that a will go down from the initial value to 0 inclusive.
  • it is more consistent because it has the same behaviour for 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.
chqrlie
  • 131,814
  • 10
  • 121
  • 189