-5

I thought I understand how postfix and prefix works until I encounter this

#include <iostream>

using namespace std;

int main(int argc, char const *argv[]) {
    int a = 3, b = 3, c = 3;
    cout << a + a++ << endl; // = 7 Okay, makes sense to me
    cout << b + c++ << endl; // = 6 Now I'm confused

    int x = 3, y = 3;
    cout << (x++)*(x++)*(x++) << endl; // = 3*4*5 = 60 Okay I get it
    cout << (++y)*(++y)*(++y) << endl; // = 5*5*6 = 150 Wait what ? But why... ?
                                       // I thought it would be 4*5*6 or 6*6*6 or something

    return 0;
}

Is there any logical explaination for this ? Or it's some kind of undefined behaviour ?

1 Answers1

1

C++ does not provide guarantees wich argument will be produced first. When you code something like:

a + a++ 

it will be translated to

int operator+(int a1, int a2)

before a call, this function a2 and a1 must be calculated. You can't determinate which parameter will be performed fist. So, you have undefined behavior.

msc
  • 32,079
  • 22
  • 110
  • 197
voltento
  • 780
  • 9
  • 23
  • The reason for the UB is that there is no sequence point between the evaluations. Otherwise, it would be unspecified behaviour. – juanchopanza Jun 29 '17 at 06:57
  • I get it now thank you. Knowing that it is translated to `int operator+(int a1, int a2)` really helps me answer my question. – Ian Altman Jun 29 '17 at 07:22