Skip to main content
GameDev.net gamedev.net
🔒 Locked

++i /i++ Whats the difference?

Started by isiahil Oct 28, 2006 at 5:50 PM 5 replies 1.7k views
Original Post
isiahil
isiahil
Whats the difference between ++i and i++. Assuming of course I is an int?
I don't have to do nothing but live and die, everything else i choose to do- I don't know, but my dad says it alot
Zakwayda
Zakwayda
Google 'c++ pre post increment'.

[Edit: Before anyone jumps in, the above is just an example search string that happens to return a fair number of relevant hits. It's not meant to imply that these operators are unique to C++.]

[Edited by - jyk on October 28, 2006 6:53:29 PM]
isiahil
isiahil
Thank you. I understand now.
I don't have to do nothing but live and die, everything else i choose to do- I don't know, but my dad says it alot
by
by
from http://www.tantalon.com/pete/cppopt/asyougo.htm#PreferOperatorEquals :

Quote:
3.6: Use Prefix Operators

Objects that provide the concept of increment and decrement often provide the ++ and - - operators. There are two types of incrementing, prefix (++x) and postfix (x++). In the prefix case, the value is increased and the new value is returned. In the postfix case, the value is increased, but the old value is returned. Correctly implementing the postfix case requires saving the original value of the object - in other words, creating a temporary object. The postfix code can usually be defined in terms of the prefix code.

const T T::operator ++ (int) // postfix
{
T orig(*this);
++(*this); // call prefix operator
return (orig);
}

The clear recommendation: avoid postfix operators. In fact, you may want to declare the postfix operators in the private section of the class so that the compiler will flag incorrect usage for you automatically.
Raghar
Raghar
And this is how it looks in the assembly.

int a = 0
a++;

mov eax, 0
inc eax

int a = 0
++a;

mov eax, 0
inc eax

long a = 0;
a++;

mov rax, 0
inc rax
Promit
Promit
Slight clarification --

Raghar's code appears to have come from GCC, on a 64 bit system. That's why the last snippet has a 64 bit value and the corresponding use of the rax register.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
markr
markr
I shall post the obvious answer:

- If you don't use the return value, nothing.

If you ignore the return value from the operator, then it makes no difference whether you use ++i or i++ (Assuming it's a simple type and not an object with overloads which do different things, of course).

Mark

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.