Increment/Decrement Operators

Hi Everyone,

I'm very new to programming and I'm having a hard time wrapping my mind around a couple of example problems.

First of all, my understanding is that ++x is postfix (meaning you add one and then display the new number) and x++ is prefix (meaning you display the number and then add one). Is this correct?

Now for the sample problems I've been looking at:
1
2
3
4
5
6
7
8
What will each of the following program segments display?
1) x = 2;
   y = x++;
   cout << x << " " << y;

2) x = 2;
   y = ++x;
   cout << x << " " <<y;


For number 1, I thought x=2 y=2 and for number 2, I got x=2 and y=3

However, I think both of these wrong. Can someone please explain why? Thank you and I apologize in advance if I'm not using the correct terms.
Hi,

In y = x++; , x is assigned to y, then x is incremented. On line 4, x is 3 and y is 2.

In y = ++x; x is incremented first, then assigned to y. On line 8, x is 3 and y is 3.

You can test these by writing a small program.

++x is pre-increment, x++ is post-increment.

Note that values are not displayed until one calls std::cout

> In y = x++; , x is assigned to y, then x is incremented.

The precedence of the post-fix increment operator is higher than that of the assignment operator.
http://en.cppreference.com/w/cpp/language/operator_precedence

Note that the precedence of the postfix increment operator is higher than that of the prefix increment operator.

Also note:
Precedence and associativity are compile-time concepts and are independent from order of evaluation, which is a runtime concept. http://en.cppreference.com/w/cpp/language/operator_precedence

"As-if" : http://en.cppreference.com/w/cpp/language/as_if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    struct A // note: increment and assignment have observable side effects
    {
        A& operator++ () { std::cout << "then prefix increment => " ; return *this ; }
        A operator++ (int) { A temp(*this) ; std::cout << "first postfix increment => " ; return temp ; }
        A& operator= ( const A& ) { std::cout << "and finally assignment\n" ; return *this ; }
    };

    A x ;
    A y ;

    y = ++x++ ; // note that this wouldn't compile if the type of x were int
                // because x++ which is parsed first results in a prvalue
                // parsed as y = ( ++ (x++) )
}

first postfix increment => then prefix increment => and finally assignment

http://coliru.stacked-crooked.com/a/a8b3e510ed65861f
Last edited on
Topic archived. No new replies allowed.