# Increment/decrement operators

> C++ Atlas: `cppatlas.com/w/cpp/language/operator_incdec` | Source: https://en.cppreference.com/w/cpp/language/operator_incdec | Domain: Language | Standards: C++11, C++17, C++20

Increment/decrement operators increment or decrement the value of the object.

## Executive Mental Model (Study Companion)

**Core Intuition:** A prvalue in C++17+ is not an object in memory—it is an unmaterialized recipe to initialize a target slot.

- **Standard Era:** C++11 → C++17 → C++23
- **Primary ISO Clauses:** [basic.lval], [conv.rval], [class.copy.elision], [dcl.type.decltype]
- **CppCon Talk Angle:** Show how C++17 reversed the arrow: previously prvalues were temporary objects we tried to elide away; now prvalues only become objects when materialization is forced.
- **Common Audience Trap:** Conflating an identifier's declared type (Widget&&) with its expression value category (lvalue inside the function body).
- **Stage Takeaway:** Never write return std::move(local); — it turns an implicit move-eligible lvalue into an explicit xvalue that blocks NRVO.

## Memory Map Walkthrough: C++17 Value Category Taxonomy & Materialization

C++17 classifies every expression along two orthogonal axes: glvalue (has identity, you can take its address or distinguish it from another object) and rvalue (eligible to be moved from). An lvalue has identity and cannot be moved from implicitly; a prvalue has no identity yet because it is an unmaterialized initialization recipe; an xvalue sits at the intersection of both—an expiring object that already occupies memory and can have its resources pilfered. Temporary materialization conversion converts a prvalue into an xvalue only at the exact boundary where an object identity is required, such as binding a reference or accessing a member.

### Identity vs. movability ([basic.lval] §7.2.1)

Forget 'left side vs right side of an assignment'. In modern C++, an expression is classified by two orthogonal questions: Does evaluation determine the identity of an existing object or function (glvalue)? And may its resources be reused because nothing else observes it afterward (rvalue)?

An lvalue has identity but is not movable. A prvalue ('pure rvalue') is an unmaterialized computation or initializer with no address of its own. An xvalue ('eXpiring value') is the overlap: an object that already exists in memory whose lifetime is about to end or was explicitly cast via std::move.

*Type vs. value category orthogonality:*
```cpp
void consume(Widget& w);   // binds lvalues
void consume(Widget&& w);  // binds rvalues (xvalue or prvalue)

void relay(Widget&& param) {
    // 'param' has type Widget&&, yet the expression 'param' is an LVALUE
    // because it has a name and an addressable location.
    consume(param);            // calls consume(Widget&)
    consume(std::move(param)); // xvalue -> calls consume(Widget&&)
}
```

**Key takeaway:** Named rvalue references are always lvalues inside expressions; only unnamed rvalue references (like std::move's return value) are xvalues.

### C++17 deferred temporary materialization ([conv.rval] & [class.copy.elision])

Prior to C++17, Widget w = Widget(42); conceptually created a temporary Widget, called the move constructor into w, and then allowed the compiler to elide that move—which still forced Widget's move constructor to be accessible.

C++17 fixed this at the grammar level. Widget(42) is a prvalue initialization recipe passed down to w's storage slot. No temporary object exists unless something forces temporary materialization ([conv.rval]), such as binding to const Widget& or reading .field on a temporary.

*Non-copyable, non-movable type returned by value:*
```cpp
struct Locked {
    int token;
    explicit Locked(int t) : token(t) {}
    Locked(const Locked&) = delete;
    Locked(Locked&&) = delete;
};

Locked make_locked() {
    return Locked{99}; // Legal since C++17: initializes caller slot directly
}

Locked x = make_locked(); // Zero moves, zero copies required
```

**Key takeaway:** Prvalue chains (make() -> make() -> variable) collapse into a single in-place construction at the final destination.

## Official Specification Summary (cppreference)

Increment/decrement operators increment or decrement the value of the object.

| Operator name | Syntax | Overloadable | Prototype examples (for `class T`) |   |
| --- | --- | --- | --- | --- |
| Operator name | Syntax | Overloadable | Inside class definition | Outside class definition |
| pre-increment | `++a` | Yes | `T& T::operator++();` | `T& operator++(T& a);` |
| pre-decrement | `--a` | Yes | `T& T::operator--();` | `T& operator--(T& a);` |
| post-increment | `a++` | Yes | `T T::operator++(int);` | `T operator++(T& a, int);` |
| post-decrement | `a--` | Yes | `T T::operator--(int);` | `T operator--(T& a, int);` |
| **Notes** - Prefix versions of the built-in operators return *references* and postfix versions return *values*, and typical user-defined overloads follow the pattern so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including `void`). - The `int` parameter is a dummy parameter used to differentiate between prefix and postfix versions of the operators. When the user-defined postfix operator is called, the value passed in that parameter is always zero, although it may be changed by calling the operator using function call notation (e.g., `a.operator++(2)` or `operator++(a, 2)`). |   |   |   |   |

### Prefix operators

The prefix increment and decrement expressions have the form

- `++` *expression*
- `--` *expression*

1) prefix increment (pre-increment)

2) prefix decrement (pre-decrement)

#### Built-in prefix operators

1) The expression `++x` is equivalent to `x += 1`, with the following exceptions:

   (until C++17):

   - If the type of *expression* is (possibly volatile-qualified) `bool`, *expression* is set to `true`. Such a increment is deprecated.

   (since C++17):

   - If the type of *expression* is (possibly cv-qualified) `bool`, the program is ill-formed.

   (since C++20):

   - If the type of *expression* is volatile-qualified, the increment is deprecated.

2) The expression `--x` is equivalent to `x -= 1`, with the following exceptions:

   - If the type of *expression* is (possibly cv-qualified) `bool`, the program is ill-formed.

   (since C++20):

   - If the type of *expression* is volatile-qualified, the decrement is deprecated.

#### Overloads

In overload resolution against user-defined operators, for every optionally volatile-qualified arithmetic type `A` other than `bool`, and for every optionally volatile-qualified pointer `P` to optionally cv-qualified object type, the following function signatures participate in overload resolution:

```cpp
A& operator++(A&)
bool& operator++(bool&) // (deprecated) (until C++17)
P& operator++(P&)
A& operator--(A&)
P& operator--(P&)
```

### Postfix operators

The postfix increment and decrement expressions have the form

- *expression* `++`
- *expression* `--`

1) postfix increment (post-increment)

2) postfix decrement (post-decrement)

#### Built-in postfix operators

The result of postfix increment or decrement is the value obtained by applying the lvalue-to-rvalue conversion to *expression* (before modification). The type of the result is the cv-unqualified version of the type of *expression*.

If *expression* is not a modifiable lvalue of an arithmetic type other than (possibly cv-qualified) `bool` (since C++17), or a pointer to a complete object type, the program is ill-formed.

If the type of *expression* is volatile-qualified, the increment or decrement is deprecated. (since C++20)

1) The value of *expression* is modified as if it were the operand of the prefix `++` operator.

2) The value of *expression* is modified as if it were the operand of the prefix `--` operator.

The value computation of a postfix increment or decrement is sequenced before the modification of *expression*. With respect to an indeterminately-sequenced function call, the operation of a postfix increment or decrement is a single evaluation.

#### Overloads

In overload resolution against user-defined operators, for every optionally volatile-qualified arithmetic type `A` other than `bool`, and for every optionally volatile-qualified pointer `P` to optionally cv-qualified object type, the following function signatures participate in overload resolution:

```cpp
A operator++(A&, int)
bool operator++(bool&, int) // (deprecated) (until C++17)
P operator++(P&, int)
A operator--(A&, int)
P operator--(P&, int)
```

#### Example

```cpp
#include <iostream>

int main()
{
    int n1 = 1;
    int n2 = ++n1;
    int n3 = ++ ++n1;
    int n4 = n1++;
//  int n5 = n1++ ++;   // error
//  int n6 = n1 + ++n1; // undefined behavior
    std::cout << "n1 = " << n1 << '\n'
              << "n2 = " << n2 << '\n'
              << "n3 = " << n3 << '\n'
              << "n4 = " << n4 << '\n';
}
```

Output:

```text
n1 = 5
n2 = 2
n3 = 4
n4 = 4
```

### Notes

Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules.

Because a temporary copy of the object is constructed during post-increment and post-decrement, pre-increment or pre-decrement operators are usually more efficient in contexts where the returned value is not used.

### Standard library

Increment and decrement operators are overloaded for many standard library types. In particular, every *LegacyIterator* overloads `operator++` and every *LegacyBidirectionalIterator* overloads `operator--`, even if those operators are no-ops for the particular iterator.

**overloads for arithmetic types**

- `operator++`, `operator++(int)`, `operator--`, `operator--(int)`: increments or decrements the atomic value by one (public member function of `std::atomic<T>`)
- `operator++`, `operator++(int)`, `operator--`, `operator--(int)`: increments or decrements the tick count (public member function of `std::chrono::duration<Rep,Period>`)

**overloads for iterator types**

- `operator++`, `operator++(int)`: advances the iterator (public member function of `std::raw_storage_iterator<OutputIt,T>`)
- `operator++`, `operator++(int)`, `operator+=`, `operator+`, `operator--`, `operator--(int)`, `operator-=`, `operator-`: advances or decrements the iterator (public member function of `std::reverse_iterator<Iter>`)
- `operator++` (C++11), `operator++(int)`, `operator+=`, `operator+`, `operator--`, `operator--(int)`, `operator-=`, `operator-`: advances or decrements the iterator (public member function of `std::move_iterator<Iter>`)
- `operator++`, `operator++(int)`: no-op (public member function of `std::front_insert_iterator<Container>`)
- `operator++`, `operator++(int)`: no-op (public member function of `std::back_insert_iterator<Container>`)
- `operator++`, `operator++(int)`: no-op (public member function of `std::insert_iterator<Container>`)
- `operator++`, `operator++(int)`: advances the iterator (public member function of `std::istream_iterator<T,CharT,Traits,Distance>`)
- `operator++`, `operator++(int)`: no-op (public member function of `std::ostream_iterator<T,CharT,Traits>`)
- `operator++`, `operator++(int)`: advances the iterator (public member function of `std::istreambuf_iterator<CharT,Traits>`)
- `operator++`, `operator++(int)`: no-op (public member function of `std::ostreambuf_iterator<CharT,Traits>`)
- `operator++`, `operator++(int)`: advances the iterator to the next match (public member function of `std::regex_iterator<BidirIt,CharT,Traits>`)
- `operator++`, `operator++(int)`: advances the iterator to the next submatch (public member function of `std::regex_token_iterator<BidirIt,CharT,Traits>`)

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| CWG 2855 | C++98 | usual arithmetic conversions are applied for built-in pre-increment and pre-decrement, but were not applied for their postfix counterparts[1] | also applied |
| CWG 2901 | C++98 | lvalue-to-rvalue conversions were not applied for built-in post-increment and post-decrement | applied |

1. ↑ The prefix `++x` is equivalent to `x += 1`, and the latter is applicable for usual arithmetic conversions (i.e. yield a common type between `decltype(x)` and `int`). However, the effect of the postfix `x++` is simply “adding one to `x`”, there is no binary operator present, so no usual arithmetic conversions will take place.

### See also

[Operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence)

[Operator overloading](https://en.cppreference.com/w/cpp/language/operators)

| Common operators |   |   |   |   |   |   |
| --- | --- | --- | --- | --- | --- | --- |
| [assignment](https://en.cppreference.com/w/cpp/language/operator_assignment) | **increment decrement** | [arithmetic](https://en.cppreference.com/w/cpp/language/operator_arithmetic) | [logical](https://en.cppreference.com/w/cpp/language/operator_logical) | [comparison](https://en.cppreference.com/w/cpp/language/operator_comparison) | [member access](https://en.cppreference.com/w/cpp/language/operator_member_access) | [other](https://en.cppreference.com/w/cpp/language/operator_other) |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a \|= b a ^= b a <<= b a >>= b` | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a \| b a ^ b a << b a >> b` | `!a a && b a \|\| b` | `a == b a != b a < b a > b a <= b a >= b a <=> b` | `a[...] *a &a a->b a.b a->*b a.*b` | function call `a(...)` |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a \|= b a ^= b a <<= b a >>= b` | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a \| b a ^ b a << b a >> b` | `!a a && b a \|\| b` | `a == b a != b a < b a > b a <= b a >= b a <=> b` | `a[...] *a &a a->b a.b a->*b a.*b` | comma `a, b` |
| `a = b a += b a -= b a *= b a /= b a %= b a &= b a \|= b a ^= b a <<= b a >>= b` | `++a --a a++ a--` | `+a -a a + b a - b a * b a / b a % b ~a a & b a \| b a ^ b a << b a >> b` | `!a a && b a \|\| b` | `a == b a != b a < b a > b a <= b a >= b a <=> b` | `a[...] *a &a a->b a.b a->*b a.*b` | conditional `a ? b: c` |
| Special operators |   |   |   |   |   |   |
| [`static_cast`](https://en.cppreference.com/w/cpp/language/static_cast) converts one type to another related type [`dynamic_cast`](https://en.cppreference.com/w/cpp/language/dynamic_cast) converts within inheritance hierarchies [`const_cast`](https://en.cppreference.com/w/cpp/language/const_cast) adds or removes [cv](https://en.cppreference.com/w/cpp/language/cv)-qualifiers [`reinterpret_cast`](https://en.cppreference.com/w/cpp/language/reinterpret_cast) converts type to unrelated type [C-style cast](https://en.cppreference.com/w/cpp/language/explicit_cast) converts one type to another by a mix of `static_cast`, `const_cast`, and `reinterpret_cast` [`new`](https://en.cppreference.com/w/cpp/language/new) creates objects with dynamic storage duration [`delete`](https://en.cppreference.com/w/cpp/language/delete) destructs objects previously created by the new expression and releases obtained memory area [`sizeof`](https://en.cppreference.com/w/cpp/language/sizeof) queries the size of a type [`sizeof...`](https://en.cppreference.com/w/cpp/language/sizeof...) queries the size of a [pack](https://en.cppreference.com/w/cpp/language/parameter_pack) (since C++11) [`typeid`](https://en.cppreference.com/w/cpp/language/typeid) queries the type information of a type [`noexcept`](https://en.cppreference.com/w/cpp/language/noexcept) checks if an expression can throw an exception (since C++11) [`alignof`](https://en.cppreference.com/w/cpp/language/alignof) queries alignment requirements of a type (since C++11) |   |   |   |   |   |   |

- [C documentation for Increment/decrement operators](https://en.cppreference.com/w/c/language/operator_incdec)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Debate why teaching 'lvalue means left-hand side of =' actively breaks programmers once const variables and std::move enter the picture.
- Walk through how C++17 deferred materialization makes non-movable types like std::atomic<int> returnable by value.
- Quiz each other on why "hello" is an lvalue and why return std::move(local) is a classic performance pessimization.

### Trap 1: [lex.string] §5.13.5 (standard-lawyer)

What is the value category and exact type of the string literal expression "cppcon"?

```cpp
auto p = &"cppcon";
```

A. prvalue of type const char*
B. lvalue of type const char[7]
C. prvalue of type const char[7]
D. xvalue of type const char(&)[7]

**Standard Answer (B):** lvalue of type const char[7]

**Why:** Unlike numeric literals such as 42 (which are prvalues), string literals have static storage duration in read-only memory. They are lvalues of array type const char[N] including the null terminator, which is why taking &"cppcon" compiles cleanly.

*CppCon speaker note:* Great opening warm-up slide at CppCon: 80% of the room picks prvalue by analogy with integer literals.

### Trap 2: [dcl.type.decltype] §9.2.9.6 (subtle)

Given int x = 10;, what are the deduced types of a and b below?

```cpp
int x = 10;
decltype(x)   a = x;
decltype((x)) b = x;
```

A. a is int, b is int
B. a is int&, b is int&
C. a is int, b is int&
D. a is int, b is int&&

**Standard Answer (C):** a is int, b is int&

**Why:** decltype has two rules: on an unparenthesized id-expression (x), it yields the declared type (int). Wrapping parentheses turns (x) into a general expression, where decltype yields T& for lvalues, T&& for xvalues, and T for prvalues.

### Trap 3: [class.copy.elision] §11.9.6 (cppcon-stage)

In C++17 and later, what happens when returning a named local variable via return std::move(buf);?

```cpp
std::string build() {
    std::string buf = "long heap string...";
    return std::move(buf);
}
```

A. Faster than return buf; because it forces a move instead of a copy
B. Prevents NRVO and forces a move construction instead of zero-cost in-place construction
C. Undefined behavior because buf is destroyed before the move finishes
D. Triggers guaranteed C++17 copy elision

**Standard Answer (B):** Prevents NRVO and forces a move construction instead of zero-cost in-place construction

**Why:** NRVO (Named Return Value Optimization) only applies when the return operand is the plain name of an automatic local variable. Wrapping it in std::move(buf) changes the expression to a function call yielding an xvalue, blocking NRVO and forcing an actual move constructor call (-Wpessimizing-move).

*CppCon speaker note:* Emphasize: plain return buf; already moves implicitly if NRVO doesn't happen, so std::move here can only hurt.

### Trap 4: [expr.ref] §7.6.1.5 (standard-lawyer)

Given struct S { int m; }; and a function S make_s();, what is the value category of make_s().m?

```cpp
struct S { int m; };
S make_s();
// What is make_s().m ?
```

A. lvalue
B. prvalue
C. xvalue
D. Ill-formed because make_s() is unmaterialized

**Standard Answer (C):** xvalue

**Why:** Member access E1.E2 on a prvalue E1 first triggers temporary materialization ([conv.rval]), turning make_s() into a temporary xvalue. A non-static data member access on an rvalue yields an xvalue designating that subobject.

### Trap 5: [expr.pre.incr] & [expr.post.incr] (subtle)

For built-in int i = 0;, which expression is well-formed C++?

```cpp
int i = 0;
```

A. &(i++)
B. (i++) = 5
C. ++ ++i
D. int& r = i++;

**Standard Answer (C):** ++ ++i

**Why:** Built-in prefix ++i modifies i and yields an lvalue referring to i, so chaining ++ ++i mutates i twice validly. Built-in postfix i++ produces a prvalue copy of the old value, which cannot have its address taken, be assigned to, or bind to a non-const lvalue ref.

---
Attribution: content from https://en.cppreference.com/w/cpp/language/operator_incdec (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.