The pointer does not show the updated value when adding a variable to 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;
}

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 can hardly understand CASE 2 and CASE 3. Can someone explain why in both cases it is not updated cwith the new value?

+4
source share
2 answers

The ordering of the operands is not specified, and you modify the object and read it without these operations.

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

+5
source

, , . , .

undefined, , , .

+1

Source: https://habr.com/ru/post/1676596/


All Articles