CKTIS / C++
Increment operator ++
The ++ operator increments its operand. For built-in types, ++x provides the modified object, whereas x++ produces a copy of the previous value. Learn the operand requirements, the distinction between the two forms, and their basic restrictions.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
++x
x++For arithmetic operands, the built-in ++ operator adds 1, but that does not guarantee a stored value exactly one greater. In C++23, incrementing an unsigned int at its maximum wraps to 0, floating-point rounding can leave the value unchanged, and incrementing an int at INT_MAX has undefined behavior.
The prefix form ++x is equivalent to x += 1: it modifies x, and its result is an lvalue referring to the same object after modification. The postfix form x++ also modifies x, but its result is a prvalue containing a copy of the previous value. Computing that old value is sequenced before the modification; this does not mean the change is deferred until the next statement.
The operand must be a modifiable lvalue. Its type must be either an arithmetic type other than bool or a pointer type pointing to a complete object type. You therefore cannot increment a literal, a bool value, a pointer prvalue, or a const-qualified object, including a pointer object that is itself const-qualified. Using built-in ++ with a volatile-qualified operand is deprecated.
For a pointer, ++ advances by one element, not one byte. The result must point to an element of the same array or one past its end. For pointer arithmetic, an object that is not an array element is treated as the sole element of a one-element array. A pointer to such an object can therefore be incremented to form a one-past-the-end pointer. A one-past-the-end pointer must not be dereferenced or incremented further. In the example, before receives 5, after which x is 6; then ++x changes x to 7, so after receives 7.
Class types can define their own operator++. Typical member declarations are T& operator++() for prefix and T operator++(int) for postfix; the extra int parameter distinguishes the forms and receives 0 when using the notation x++. These overloads need not preserve the built-in operator's semantics or return the types shown.
Examples
#include <iostream>
int main() {
int x = 5;
int before = x++;
int after = ++x;
std::cout << "before=" << before << '\n';
std::cout << "after=" << after << '\n';
std::cout << "x=" << x << '\n';
}
Result
before=5 after=7 x=7
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.