Increment Operator

What Is the Prefix Increment Operator?

The prefix increment operator adds one before the value is used. Learn how ++x works in C++, how it differs from x++, and why it matters in code.

On this page
  1. The short answer
  2. Basic syntax
  3. How it behaves in an expression
  4. Prefix versus postfix
  5. Using the prefix form with pointers
  6. Mistakes to avoid
  7. Quick summary

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 + ++x has 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

  • ++x adds 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.

The complete guide to increment operator

The Increment Operator in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Inheritance in C++

A practical guide to inheritance in C++: the syntax, access specifiers, constructor order, virtual functions and common mistakes, with short code examples.

Inheritance 7 min read