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 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.

Best practice

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

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

  • Nikola

    Hello,

    Not technically important but there is a mistake in the first sentence of the "Side effects" section.

    A function or expression is said to have a side effect if IT does

  • Attila

    I feel like the third paragraph from the bottom should be outlined as a "Rule" shown in lecture 0.2

  • Murat

    When running both commented lines (individually), the output is 2. But you said that it would be 1 or 2 (depending on which is commented out).

    • Pre C++17, both lines cause undefined behavior. There's no point in talking about what the result could be, because anything could happen.

      As I understand it, since C++17 this is guaranteed

      Either I am wrong or gcc and clang are generating invalid warnings. Maybe someone else can clear up.
      My assumption is based on rule 20 here https://en.cppreference.com/w/cpp/language/eval_order#Rules

  • DecSco

    Does this produce undefined behaviour?

    On my machine, it works fine. But I'm not sure that's universal, given that the execution may already have returned to the function call.

    • This is well-defined.

      > the execution may already have returned to the function call
      Mind elaborating? Your program is executed sequentially, it can't run 2 things at the same time.

      • DecSco

        Cheers. That's what I needed to know.
        What I meant is that at the time when the return statement gets executed, and the value of "identifier" is supposed to be returned to the caller, it still has to be incremented. So if the execution were to return to the caller at the point at which the value is correct, then the increment would be lost, because the execution has already left the function.
        So the compiler would actually have to implement it as something like

        Correct?

        • Side effect are applied when the function ends, `main` won't run before `identifier` has been incremented. You'll only lose information if you modify a variable multiple times in 1 statement, but you're not doing that.

  • I found these examples really amusing and informative. Thanks for the lesson.

  • daileyj93

    "For more information on undefined behaviors, revisit the “Undefined Behavior” section of lesson 1.3 -- Introduction to variables."

    It looks like undefined behavior is now lesson 1.6 -- Uninitialized variables and undefined behavior, not lesson 1.3 anymore.

  • zakqux

    Can you clarify this? Don't understand quite how x=1...

    • postfix++ returns the value the variable had before it has been increased.
      ++prefix returns the value the variable has after having been increased.

      Both variants increase the variable by one, only the return value is different. Use ++prefix unless you need postfix++. postfix++ is slower.

  • Jörg

    Hi, I heard that c++17 introduced some changes to the evaluation order when working with side effects. Do you know any of this? Is

    still undefined?

    • Alex

      It did introduce some evaluation order changes, and some of the expressions that yielded undefined results now resolve determinately. I don't know if those particular expressions are affected or not. The best practice doesn't change though -- don't use a variable with a side effect applied to it more than once in an expression.

  • Senna

    Hi,
    I've read previously lessons, even though they're updated do I gotta study them again ?

Leave a Comment

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