-2

I have written a code in c++ to check the variable increment (Screenshot added). In line 13 when I use "++x" in printing function to print the value of x and y. The value I'm getting is not equal but the memory address is same. In line 17 I've incremented y as ++y and I got my expected equal ans (Screenshot added) My Code Screenshot.

What is the reason for not getting the unexpected ans in line 13?

My Code: https://gist.github.com/mefahimrahman/7fb0f45ae1f45caeb97d5aaeb39c4833

#include<bits/stdc++.h> 
using namespace std;
int main()
{
    int x = 7, &y = x; 
    cout << "Whithout Increment: ";
    cout << &x << " " << &y << endl;
    cout << x << " " << y << endl;
    --x;

    cout << "After x Increment: ";
    cout << &x << " " << &y << endl;
    cout << ++x << " " << y << endl;

    y++; cout << "After y Increment: ";
    cout << &x << " " << &y << endl; 
    cout << x << " " << ++y << endl;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
mefahimrahman
  • 197
  • 2
  • 6
  • 29

1 Answers1

3

You are assuming that in

cout << ++x << " " << y << endl;

++x will be evaluated before the value of y is accessed. In other words you are assuming that your output expression is evaluated left to right. But this is not necessarily the case. Change your code to this

++x;
cout << x << " " << y << endl;

and you will get the output you expect.

Also newbies sometimes assume that ++x means the x will be incremented before anything else. But again this is not true, ++x just means that x will be incremented before the value of x is taken, not before anything else.

john
  • 85,011
  • 4
  • 57
  • 81
  • Isn't the original code also undefined behavior? See draft n4659, 4.6/17 (was 1.9/15 in [this answer](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points)): **If a side effect** [the ++] **on a memory location** [x] **is unsequenced** [which sub-expressions like the operands of "<<" are] **relative to [...] a value computation** [taking y's value as operand of "<<"] **using the value of any object in the same memory location** [y refers to the memory locattion of x] [...] **the behavior is undefined.** Example in the standard: `i = i++ + i;` – Peter - Reinstate Monica Sep 21 '18 at 11:53
  • @PeterA.Schneider You're probably right, but I think the exact diagnosis varies depends on the version of C++ so I given up trying to keep track. I think (don't quote me) that the OP's code becomes well defined with C++17. – john Sep 21 '18 at 12:28