Saturday, April 14, 2007

C++ or ++C (read i++ or ++i)

Pre-increment and post-increment : achieve "almost" the same end result with a little difference. It is always adviced to use the pre-increment form in expressions where you do not care what value the expression ought to use - the new incremented one or the older value prior to increment. Also when it matters, if you need the former then use the pre-increment form and if the latter use the post-increment form. That is the basic difference.

The post increment form has a drawback of generating a temporary (yeah, that can be optimized by the optimizer but still).

To understand the difference and when to use which form, you may find this Codeguru FAQ entry quite helping : C++ Operator: Why should I use '++i' instead of 'i++'?

Have fun!

2 comments:

Anonymous said...

"in expressions where you do not care what value the expression ought to use - the new incremented one or the older value prior to increment."

Not to be a pain, but if you don't care then you shouldn't use either... You should always care (and be aware) of what you're doing and what is necessary.

BTW, nice site ;)

abnegator said...

@Petter : Thank you very much, Petter, for the visit. :) And your comments are never a pain. I have learnt a lot from you. Stay within reach. Cheers! :)