#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;
}
输出:
案例1:
a is 5. b is 5. c is 5.
a is 10. b is 10. c is 10.
案例2:
a is 5. b is 5. c is 5.
a is 11. b is 11. c is 10.
案例3:
a is 5. b is 5. c is 5.
a is 11. b is 10. c is 10.
我理解案例1.但我很难理解案例2和案例3.有人可以解释为什么在这两种情况下都不会c
更新新值?
答案 0 :(得分:5)
操作数的评估顺序未指定,您正在修改对象并在不对这些操作进行排序的情况下读取它。
因此,您的程序未定义为cout << a << a++;
,任何事情都可能发生。
答案 1 :(得分:1)
我认为你的问题是由于所谓的序列点。您可以在this answer中详细阅读该文章,但简而言之,它基本上说明了表达式元素的顺序或评估。
在你的情况下更新这个订单是未定义的,尽管有些编译器似乎是从右到左。