Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 171 ยท Operators

Assignment and Increment Operators

Master C++ assignment, compound assignment like += and *=, prefix vs postfix ++ and --, and the sequencing rules that make code like i = i++ so dangerous.

Programs spend most of their time changing values: adding to a total, counting loop iterations, moving to the next item. C++ gives you a compact set of operators for this: plain assignment =, compound assignments such as += and *=, and the famous ++ and -- that gave the language its name.

They are easy to use, but they hide some subtle rules. Assignment is an expression with a value, which makes if (x = 5) compile. ++i and i++ return different things. And combining several changes to the same variable in one expression has been a source of undefined behavior for decades. This lesson explains all of it, including what changed in C++17.

Simple assignment

x = value evaluates the right-hand side and stores it in the object on the left. The left side must be something that can be modified, such as a variable (an lvalue). 5 = x or a + b = 3 do not compile.

Don't confuse assignment with initialization. int x = 5; creates x with the value 5; x = 7; later replaces the value of an existing object. The difference becomes important with classes and const variables (a const int can be initialized but never assigned), which Variables introduced.

In C++, an assignment is also an expression: its value is the variable that was just assigned. That has two consequences.

Chained assignment works. Assignment groups right to left, so a = b = c = 0 means a = (b = (c = 0)): c gets 0, then b gets the value of c, then a gets the value of b.

An assignment can appear inside a condition. This is sometimes deliberate, as in a read loop, and sometimes a bug, as in if (x = 5) when you meant ==.

C++ Assignment is an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The read-loop style while ((n = n / 2) > 0) needs the extra parentheses: without them, > would bind first because comparison has higher precedence than assignment.

if (x = 5) is almost always a bug. It assigns 5 to x, and since 5 is non-zero the condition is always true. GCC and Clang warn about it with -Wall ("suggest parentheses around assignment used as truth value"). Never ignore that warning. If you really want to assign inside a condition, C++17's if with an initializer is clearer: if (int r = compute(); r > 0) { ... }. See if, else if and else.

Compound assignment

Updating a variable based on its own value is so common that every binary arithmetic and bitwise operator has a compound version:

Operator Same as Example (x starts at 20) New x
+= x = x + y x += 5 25
-= x = x - y x -= 5 15
*= x = x * y x *= 3 60
/= x = x / y x /= 3 6
%= x = x % y x %= 6 2
&= |= ^= bitwise and/or/xor x |= 1 21
<<= >>= shifts x <<= 2 80

The bitwise ones are covered in Bitwise Operators. Compound assignment has two advantages over writing the long form. It is shorter and states the intent ("add to x"). And the left side is evaluated only once, which matters when it's an expensive or side-effecting expression like scores[find_player(name)] += 10.

The right-hand side is evaluated completely first, so x *= a + b means x = x * (a + b), not x * a + b.

C++ Compound assignment in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

As the last lines show, += also works on std::string, where it appends. You will use that a lot in Strings with std::string.

The hidden conversion in compound assignment

x += y converts the result back to the type of x, silently. If x is an int and y is a double, the fraction is thrown away every time:

C++
int n = 10;
n *= 2.5;          // 10 * 2.5 = 25.0, stored as 25
int total = 0;
total += 0.4;      // 0.4 truncated to 0, so total stays 0

The compiler doesn't warn about this with -Wall -Wextra; only -Wconversion catches it. If a variable receives fractional amounts, give it a floating-point type. Type Conversions and Casts explains the full set of conversion rules.

Increment and decrement: ++ and --

++x adds 1 to x, and --x subtracts 1. Both come in two forms that do the same thing to the variable but produce different values as an expression:

  • Prefix ++x: increments first, and the expression's value is the new value (it actually returns x itself).
  • Postfix x++: the expression's value is the old value (a copy), and x is incremented as a side effect.

When the ++ stands alone as a statement, like ++count; or count++;, there is no difference at all. The difference only shows when you use the result.

C++ Prefix versus postfix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that each example changes the variable in one statement and reads it in another. Mixing both in a single expression is where the trouble starts, as the sequencing section at the end of this lesson shows.

Which form should you use?

For plain integers, it doesn't matter for speed: the optimizer produces identical code for i++; and ++i;. But many C++ programmers write prefix by default, especially in loops, for two reasons:

  • For class types such as iterators, postfix has to create and return a copy of the old object, which can cost something. Prefix never does.
  • Prefix says exactly what you mean: "increment". Postfix says "increment, but give me the old value".

So for (int i = 0; i < n; ++i) is the idiomatic loop header, and you'll use postfix only when you need the old value, as in next_id++.

What can be incremented?

++ and -- work on all integer and floating-point types, on pointers and iterators (where they move to the next or previous element, as you'll see in Pointers and Arrays and Iterators), and on any class that overloads them. They don't work on bool (++flag was deprecated for years and removed in C++17), on scoped enums (enum class), or on const variables.

Counting loops and the unsigned countdown trap

Increments and decrements are the heart of counting loops. Counting down with an unsigned type is a classic trap: an unsigned value is never negative, so i >= 0 is always true, and decrementing 0 wraps around to a huge number. The loop never ends (or, with an index, reads far out of bounds).

C++ Counting up and counting down safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The idiom i-- > 0 relies on postfix: it compares the old value with 0, then decrements, so the body sees size - 1 down to 0. GCC warns about the always-true i >= 0 comparison with -Wextra ("comparison of unsigned expression in '>= 0' is always true"), another reason to compile with warnings on. In real code, a range-based for loop or std::views::reverse (see Ranges and Views) avoids index arithmetic entirely.

Remember that ++ follows the same overflow rules as +: incrementing an int that holds its maximum value is undefined behavior, while an unsigned value wraps to 0. See Arithmetic Operators.

Sequencing pitfalls: what changed in C++17

When an expression modifies a variable, C++ has to define when that modification happens relative to the other parts of the expression. The rules are called sequencing. For decades they were loose, and some innocent-looking lines were undefined behavior:

C++
i = i++;          // before C++17: undefined behavior
i = i++ + 1;      // before C++17: undefined behavior
a[i] = i++;       // before C++17: undefined behavior
x = i++ + i++;    // STILL undefined behavior today
f(i++, i++);      // well defined since C++17, but the order is unspecified

Here's the short history:

  • C++98/03 talked about sequence points: between two sequence points (roughly, the end of a full expression), modifying a variable twice, or modifying it and reading it for another purpose, was undefined behavior.
  • C++11 replaced sequence points with the sequenced before relation. It made a few cases defined (such as i = ++i), but i = i++ was still undefined.
  • C++17 added more guarantees: in a = b the right side, including all of its side effects, is sequenced before the left side; << and >> evaluate left to right; and each function argument is evaluated completely before another one starts, though their order is still unspecified. That made i = i++ well defined: it leaves i unchanged, because the old value is assigned back.

But the operands of +, *, == and most other operators are still unsequenced. Modifying a variable twice in one of them, like i++ + i++, remains undefined behavior even in C++23. The compiler may produce any result.

C++ The compiler warns about tangled side effects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This example compiles with a warning on purpose: GCC reports operation on 'i' may be undefined (-Wsequence-point), even in C++23 mode where this particular line is defined. That's a good thing. Code like this confuses every reader, and the same pattern inside + or * really is undefined. The professional rule is simple: modify a variable at most once per expression, and don't read it elsewhere in that expression. Use separate statements instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do a and b hold after int a = 5; int b = a++;?

    Postfix ++ yields the old value (5) for b, and a is incremented to 6.
  2. 2. What is x after int x = 3; x *= 2 + 1;?

    The whole right-hand side is evaluated first, so this is x = x * (2 + 1) = 9.
  3. 3. What does int total = 0; total += 0.4; total += 0.4; total += 0.4; leave in total?

    Each time, 0 + 0.4 = 0.4 is converted back to int, which truncates to 0. The total never grows. Use a double for fractional amounts.
  4. 4. Why is for (std::size_t i = n - 1; i >= 0; --i) a bug?

    Unsigned types can't be negative. After 0, --i wraps to the largest value, and the condition stays true forever.
  5. 5. Which line is still undefined behavior in C++23?

    The operands of + are unsequenced, so modifying i twice inside them is undefined. C++17 made the assignment cases defined, though they are still poor style.

Summary

  • = stores a value in an existing object. An assignment is an expression whose value is the assigned variable, so a = b = 0 works and groups right to left.
  • if (x = 5) assigns instead of comparing; heed the compiler's warning.
  • Compound operators (+=, -=, *=, /=, %=, and the bitwise ones) evaluate the right side first, evaluate the left side once, and silently convert the result back to the left side's type.
  • ++x returns the new value; x++ returns a copy of the old value. Standing alone they're identical; prefer prefix unless you need the old value.
  • Count down with unsigned types using i-- > 0, or use a signed counter.
  • C++17 made i = i++ and a[i] = i++ defined, but i++ + i++ is still undefined. Modify a variable at most once per expression.

Next: Comparison and Logical Operators, where you'll compare values, combine conditions and meet the spaceship operator <=>.