View Poll Results: a++ or ++a?

Voters

35. You may not vote on this poll

a++

2365.71%

++a

1028.57%

a = a + 1

12.86%

a = 1 + a

00%

never uses them

12.86%

a++ or ++a

This is a discussion on a++ or ++a within the A Brief History of Cprogramming.com forums, part of the Community Boards category; ^ I agree... but please don't say 'natural'... after another thread I started, I plan on completely deleting the word ...

Originally posted by Prelude >Indeed.
I think you missed the point. A well known micro-optimization technique is to invert the loop, starting from the end and decrementing. This is on the assumption that some machines have a special instruction for decrementing and comparing with zero and a reversed loop is a good hint to the compiler to use those instructions.

Yes, but the only difference is a single subtraction operation done by the processor. If you need to optimize things like that, do what Sebastiani said and use asm.

I do tend to use ++a (or --a) unless I need the old value. Although any good optimizing compiler should make no distinction, ++a is:

* As readable as a++
* Never worse in performance than a++ and sometimes better

I agree, increment/decrement is not the place to look at optimizing, but this is not your typical optimization, because there is no benefit from a++ if you don't need the old value. Optimization is all about making decisions based on tradeoffs. For example, do you want a fast program or a small one? Do you want to take advantage of processor-specific features that might slow your program down on other systems? Do you want to keep your classes very uncoupled, making code changes easier and bugs rarer, or do you need the added speed that tighter coupling can provide?

In this case, if there is only one side of the story -- if ++a is always as good and possibly better (at least in cases where ++ has the typical meaning), then I think ++a is the way to go.

According to the discussion of whether ++a is faster than a++ I have made a few tests. i compiled the test program below (without optimizations) and got the following results:

EDIT:
Old code, see next page for updated test

As you can see, not much differs from them. They have the same instructions run, only in a different order. My conclusion from this is they are both running at the same speed. If someone else have anything to add, please do.