Search

5.4 — Increment/decrement operators, and side effects

Incrementing and decrementing variables

Incrementing (adding 1 to) and decrementing (subtracting 1 from) a variable are both so common that they have their own operators.

Operator Symbol Form Operation
Prefix increment (pre-increment) ++ ++x Increment x, then return x
Prefix decrement (pre-decrement) –– ––x Decrement x, then return x
Postfix increment (post-increment) ++ x++ Copy x, then increment x, then return the copy
Postfix decrement (post-decrement) –– x–– Copy x, then decrement x, then return the copy

Note that there are two versions of each operator -- a prefix version (where the operator comes before the operand) and a postfix version (where the operator comes after the operand).

The prefix increment/decrement operators are very straightforward. First, the operand is incremented or decremented, and then expression evaluates to the value of the operand. For example:

This prints:

6 6

The postfix increment/decrement operators are trickier. First, a copy of the operand is made. Then the operand (not the copy) is incremented or decremented. Finally, the copy (not the original) is evaluated. For example:

This prints:

6 5

Let’s examine how this line 6 works in more detail. First, a temporary copy of x is made that starts with the same value as x (5). Then the actual x is incremented from 5 to 6. Then the copy of x (which still has value 5) is returned and assigned to y. Then the temporary copy is discarded.

Consequently, y ends up with the value of 5 (the pre-incremented value), and x ends up with the value 6 (the post-incremented value).

Note that the postfix version takes a lot more steps, and thus may not be as performant as the prefix version.

Here is another example showing the difference between the prefix and postfix versions:

This produces the output:

5 5
6 4
6 4
6 4
7 3

On the 8th line, we do a prefix increment and decrement. On this line, x and y are incremented/decremented before their values are sent to std::cout, so we see their updated values reflected by std::cout.

On the 10th line, we do a postfix increment and decrement. On this line, the copy of x and y (with the pre-incremented and pre-decremented values) are what is sent to std::cout, so we don’t see the increment and decrement reflected here. Those changes don’t show up until the next line, when x and y are evaluated again.

Best practice

Strongly favor the prefix version of the increment and decrement operators, as they are generally more performant, and you’re less likely to run into strange issues with them.

Side effects

A function or expression is said to have a side effect if it does anything that persists beyond the life of the function or expression itself.

Common examples of side effects include changing the value of objects, doing input or output, or updating a graphical user interface (e.g. enabling or disabling a button).

Most of the time, side effects are useful:

The assignment operator in the above example has the side effect of changing the value of x permanently. Even after the statement has finished executing, x will still have the value 5. Similarly with operator++, the value of x is altered even after the statement has finished evaluating. The outputting of x also has the side effect of modifying the state of the console, as you can now see the value of x printed to the console.

However, side effects can also lead to unexpected results:

C++ does not define the order in which function arguments are evaluated. If the left argument is evaluated first, this becomes a call to add(5, 6), which equals 11. If the right argument is evaluated first, this becomes a call to add(6, 6), which equals 12! Note that this is only a problem because one of the arguments to function add() has a side effect.

There are other cases where C++ does not specify the order in which certain things are evaluated (such as operator operands), so different compilers may exhibit different behaviors. Even when C++ does make it clear how things should be evaluated, historically this has been an area where there have been many compiler bugs. These problems can generally all be avoided by ensuring that any variable that has a side-effect applied is used no more than once in a given statement.

Warning

C++ does not define the order of evaluation for function arguments or operator operands.

Warning

Don’t use a variable that has a side effect applied to it more than once in a given statement. If you do, the result may be undefined.


5.5 -- Comma and conditional operators
Index
5.3 -- Modulus and Exponentiation

235 comments to 5.4 — Increment/decrement operators, and side effects

  • Ahmed

    so functions arguments don't follow the operator precedence and associativity?
    because if it does then this

    should evaluate ++x first since it has higher precedence than the +x which in this case shouldn't be a problem.

  • Hi

    Why does this:

    produce "10 and 9"?

    • Alex

      > Don’t use a variable that has a side effect applied to it more than once in a given statement. If you do, the result may be undefined.

  • Alexandra

    Hi,

    Can you help me understand how the value of x is changing in the following example? This makes me very confused :(.

    The output of running it is:

    Initialize x: x=0
    Before adding value to x: x=0
    After adding value to x: x=1
    x=2
    Print the values of x before/after adding 1:
    Before adding value to x: x=2
    After adding value to x: x=3
    43
    Before adding value to x: x=4
    After adding value to x: x=5
    54

    I would have expected to have the following result for the last two lines of code:
    23
    and
    56

    Thank you!

    • nascardriver

      The order of evaluation in line 24 and 25 is unspecified. If you want to access `object` in a specific order, you need to do so in separate lines.

  • SuperNoob

    Yeah it's clear now. Thank you!

  • SuperNoob

    Some things have been bugging me for a while. Consider the programs below:

    Program 1:

    #this Program 1 works

    Program 2:

    #this Program 2 works too. i mean runs successfully and doesn't print anything.

    cout function is forward declared inside the std namespace residing in the iostream header. The main definition is defined somewhere in my system. And I thought the std namespace is unique. But as Program 2 works too, does that mean there is another std namespace inside the cmath header? Why did they do so? They could just use something like "std_io" namespace for iostream, and "std_cmath" namespace for cmath. Then it would be easier for us to detect which is what at the first glance. So I guess, these goes something like:

    <iostream>

    <cmath>

    So the compiler knows which std we are referring to. Am I right?

    • nascardriver

      Namespaces can and often are used across multiple files. There's a `namespace std` in <iostream> and there's a `namespace std` in <cmath> like you've shown. This counts as the same namespace in both files. It doesn't matter how often a namespace scope is opened or closed, it is the same namespace as long as the name (including parent namespaces) is the same.

      The standard library uses sub-namespaces for some new libraries, eg. `std::chrono`, `std::filesystem`, `std::ranges`. I don't know why this wasn't done from the very start.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]