How will you best differentiate the two?
i++; //and
++i;
Printable View
How will you best differentiate the two?
i++; //and
++i;
++i increments i and then uses the new value, while i++ uses the old value and then increments i.
eg.
Code:int i = 10;
cout << i-- << endl; //prints 10 (returned THEN decremented)
cout << --i << endl; //prints 8 (decremented THEN returned)
Code:int i = 0;
//first example, b will be 1
int b = ++i;
//second example, b will be 0
int b = i++;
Note also that in C++, when you are using --x or ++x for your own class (e.g. an iterator), then the calculation is simpler than for x++ or x--, because the latter requires a temporary copy of the value to be returned, and this adds extra work for the compiler. This has been discussed quite a lot - many C++ programmers therefor prefer to use --x or ++x whenever possible, even on standard base-types that aren't subject to custom operator functions [and thus have no difference in performance].
--
Mats
Actually, it will print 8, because just before that point i=9.
Uh? For starters you are worng. It prints 8. Next, did you really have a question or are you wasting our time. You seem to know the answer.