++i vs i++ in C++: same result, different timing
Short answer: both add 1 to i. The difference is what the expression itself equals: ++i hands back the new value; i++ hands back the old value before incrementing. On a line by themselves, they're identical.
Run this — the two variables start equal, and the only difference is pre- vs post-increment:
#include <iostream>
using namespace std;
int main() {
int i = 5;
cout << "i++ gives: " << i++ << ", i is now " << i << endl;
int j = 5;
cout << "++j gives: " << ++j << ", j is now " << j << endl;
return 0;
}
i++ printed 5 — the old value — and only then became 6. ++j became 6 first and printed the new value. That's the entire difference: the value of the expression.
What each one does, step by step
x = i++;is three steps: save the old value → incrementi→ assign the saved old value tox.x = ++i;is two steps: incrementi→ assign the new value tox.
In a loop? No difference at all
Both loops below print exactly the same thing, because the loop only uses the side effect (the increment), never the expression's value:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) cout << i << " ";
cout << endl;
for (int i = 0; i < 5; ++i) cout << i << " ";
cout << endl;
return 0;
}
So when does the difference actually cost you something? Not with ints — the compiler optimizes both to identical machine code. It matters with class types: i++ must keep a copy of the old value to hand back, and for a big object that copy is real work. That's why C++ style guides say: prefer ++i as a habit — it's never slower, and sometimes faster.
The famous trap: two increments in one expression
Never write things like this, even to "test" it:
i = i++ + ++i; // undefined behavior — do not use
When one variable is modified twice between two "sequence points" (loosely: within one statement, with no ordering guaranteed), the standard refuses to say what happens. Different compilers produce different answers, and optimizing compilers may produce anything. One increment per statement keeps you safe.
Interview questions on this theme
- "What does
cout << i++print?" — the old value ofi; theniis one larger. - "Which is faster, ++i or i++?" — for built-in numbers, identical after optimization; for class types, pre-increment can skip a copy.
- "Why is
i = i++broken?" — modifyingitwice in one statement without sequencing is undefined behavior. - "What is operator overloading here?" — class types define
operator++(int)(postfix, dummyintparameter) andoperator++()(prefix); the dummy parameter is how C++ tells them apart.
Practice in the playground
- Predict the output of
int a = 3; int b = a++; cout << a << b;— then run it. (Answer before you look:4and3.) - Same with
++a— what changes? - Put
i++and++iin a for loop header and confirm the outputs match.
Related: for vs while loops, why 7 / 2 equals 3, beginner interview questions.