cout 表达式中的递增地址呈现意外输出
Increment address in cout expression renders unexpected output
我不明白这里发生了什么。肯定有一些与 "flush" termen 有关的东西,但我想要一个解释。
int arr[4] {3,8,1,6};
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<endl;
cout<<&arr[0]<<endl;
cout<<&arr[1]<<'\n';
cout<<&arr[2]<<endl;
cout<<&arr[3]<<endl;
cout<<&arr[0]<<endl;
int *j = &arr[0];
cout << *j << *(++j) << *(++j) << *(++j); // HERE IS THE PROBLEM
为什么最后一条 cout
指令倾向于输出相反的数字?
在我看来像是回溯,但我不确定。
我期待 3816
作为输出,但我得到了 6618
。
表达式中
cout << *j << *(++j) << *(++j) << *(++j);
order of evaluation is not well defined, so the behaviour is undefined.
Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, more than one modifications of the same scalar in an expression without any intermediate sequence point (until C++11) that are unsequenced (since C++11)
I ran it 并输出 3816
。请注意,编译器会检测到警告标志。
如果你尝试:
cout << *j;
cout << *(++j);
cout << *(++j);
cout << *(++j);
这个顺序良好的表达式将呈现预期的输出。
我不明白这里发生了什么。肯定有一些与 "flush" termen 有关的东西,但我想要一个解释。
int arr[4] {3,8,1,6};
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<endl;
cout<<&arr[0]<<endl;
cout<<&arr[1]<<'\n';
cout<<&arr[2]<<endl;
cout<<&arr[3]<<endl;
cout<<&arr[0]<<endl;
int *j = &arr[0];
cout << *j << *(++j) << *(++j) << *(++j); // HERE IS THE PROBLEM
为什么最后一条 cout
指令倾向于输出相反的数字?
在我看来像是回溯,但我不确定。
我期待 3816
作为输出,但我得到了 6618
。
表达式中
cout << *j << *(++j) << *(++j) << *(++j);
order of evaluation is not well defined, so the behaviour is undefined.
Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, more than one modifications of the same scalar in an expression without any intermediate sequence point (until C++11) that are unsequenced (since C++11)
I ran it 并输出 3816
。请注意,编译器会检测到警告标志。
如果你尝试:
cout << *j;
cout << *(++j);
cout << *(++j);
cout << *(++j);
这个顺序良好的表达式将呈现预期的输出。