The short answer
The prefix increment operator is ++ written before a variable, as in ++x. It adds 1 to x first, and then the expression produces the new value.
Basic syntax
int x = 4;
++x; // x is now 5
How it behaves in an expression
When the result is used, the prefix form gives back the updated value:
#include <iostream>
int main() {
int x = 10;
int y = ++x; // x becomes 11, and y gets 11
std::cout << "x = " << x << ", y = " << y << "\n";
return 0;
}
The output is:
x = 11, y = 11
Prefix versus postfix
The difference shows up only when the value is used. Assume x holds 10 before each row:
| Expression | Value the expression gives | Value of x afterward |
|---|---|---|
++x |
11 | 11 |
x++ |
10 | 11 |
Both forms leave x at 11. The only difference is the value the expression produces. That value matters when the expression sits inside an assignment or a function call, such as f(++x) compared with f(x++).
Using the prefix form with pointers
Prefix is also common with pointers:
#include <iostream>
int main() {
int nums[] = {1, 2, 3};
int* p = nums;
int first = *++p; // p moves to nums[1], so first is 2
std::cout << first << "\n";
return 0;
}
The output is 2. The expression *++p moves the pointer first and then reads the element it points to. The postfix form, *p++, reads the current element and then moves the pointer, because p++ is grouped before the *.
Mistakes to avoid
- Changing the same variable twice in one expression. Code such as
++x + ++xhas undefined behavior in C++. - Using prefix when you need the old value. If you need the value from before the change, use the postfix form.
Quick summary
++xadds 1 first, then gives back the new value.- The prefix and postfix forms leave the variable in the same state. They differ in the value of the expression.
- The prefix form is handy with pointers, as in
*++p.