读书人

【求教】输出结果 及缘故

发布时间: 2013-04-02 12:35:26 作者: rapoo

【求教】输出结果 及原因

#include<iostream>
using std::cout;
using std::endl;

int fun_ptr(int* p)
{
*p = *p + 1;
return *p;
}

int fun_ref(int& ref)
{
ref = ref + 1;
return ref;
}
int main()
{
int a = 10;
int* p = &a;
int& r = a;
cout << *p<< " " << fun_ptr(p) << " " << a << endl;
cout << r << " " << fun_ref(r) << " " << a << endl;
}

[解决办法]
引用:
C/C++ code?12cout << *p<< " " << fun_ptr(p) << " " << a << endl; cout << r << " " << fun_ref(r) << " " << a << endl;
输出的顺序?问题?
我预想的结果是:10 11 11
11 12 12
这样顺序的原因是?
……


原因是cout的输出实际上是 (cout.operator<<(*p)).operator<<(fun_ptr(p));
首先计算外层调用,然后是内层调用,所以先计算后面的fun_ptr(p),然后才是前面的*P
[解决办法]
这是因为cout是从右向左压栈,对于
cout << *p<< " " << fun_ptr(p) << " " << a << endl;
这句来说,其实先执行cout << a;然后是cout << fun_ptr(p)最后 cout << *p所以才会有那个结果。
[解决办法]
依赖于子表达式求职顺序,行为未定义。

//为了说明问题,简化了一下
cout << *p<< fun_ptr(p);
/*
可能的执行顺序1:
{
int t1 = fun_ptr(p);
int t2 = *p;
(cout << t2) << t1;
}
可能的执行顺序1:
{
int t1 = *p;
int t2 = fun_ptr(p);
(cout << t1) << t2;
}
//或者其他
*/

读书人网 >C语言

热点推荐