What's the difference between var++ and ++var

This is a discussion on What's the difference between var++ and ++var within the C Programming forums, part of the General Programming Boards category; When you use for loops or a general variable incrementation, what difference does it make for the location of the ...

What's the difference between var++ and ++var

When you use for loops or a general variable incrementation, what difference does it make for the location of the "++"? That is, what's the difference between these two for loop headers and the following variable adjustments:

The only difference between prefix and postfix operators is the result of the operator. In postfix, a temporary object is created, the operation is applied, and the temporary is returned: the object before the operation is applied. In prefix, the operation is applied and the fixed object is returned, without the use of a temporary: the object after the operation is applied.

Some people think that the temporary makes postfix a poor choice. This is not so if you use an optimizing compiler. But the main difference is what the operation yields as a result, because it can make a huge difference as part of a larger expression.

Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.

That example is somewhat misleading. The for loop doesn't use the result of the increment expression. It just executes the expression for the side-effects, which of course aren't shown in both of those.

However, whenever possible, use ++var, not var++. When you've learnt enough C++ as well, you'll see why.

One more thing you should know also, when we use ' i++ ' then a temproray variable is created to store incremented value of ' i ', to assign it in i later on. while in case of ++i incremented value stores in ' i ' itself.