Search code examples
c++pointersoperator-precedence

Pointer not showing updated value when incrementing a variable in std::cout


#include <iostream>
#include <string>

using namespace std;

int main()
{
  int a = 5;
  int& b = a;
  int* c = &a;

  cout << "CASE 1" << endl;
  cout << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
  b = 10;
  cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl << endl;

  cout << "CASE 2";
  a = 5;
  cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
  b = 10;
  cout << endl << "a is " << a << endl << "b is " << ++b << endl << "c is " << *c << endl << endl;

  cout << "CASE 3";
  a = 5;
  cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
  b = 10;
  cout << endl << "a is " << a << endl << "b is " << b++ << endl << "c is " << *c << endl;
}

The output:

CASE 1:

a is 5. b is 5. c is 5.
a is 10. b is 10. c is 10.

CASE 2:

a is 5. b is 5. c is 5.

a is 11. b is 11. c is 10.

CASE 3:

a is 5. b is 5. c is 5.
a is 11. b is 10. c is 10.

I understand CASE 1. But I am having difficulty understanding CASE 2 and CASE 3. Can someone explain why doesn't c get updated with new value in both cases?


Solution

  • The evaluation order of operands is unspecified, and you're modifying an object and reading it without those operations being sequenced.

    Thus, your program is as undefined as cout << a << a++;, and anything can happen.