书上一道题,求输出结果:
#include <iostream.h>
int fun(int x, int y)
{
return x*y;
}
void main()
{
int k=5;
cout<<fun(k++,++k)<<endl;
}答案是36.
可我还是没太懂,求各位大侠帮忙解释下。
另外:这程序和下面这个难道不等价吗?#include <iostream.h>
int fun(int x, int y)
{
return x*y;
}
void main()
{
int k=5;
int a,b;
a=k++;
b=++k;
cout<<fun(a,b)<<endl;
}求分析,谢了

解决方案 »

  1.   


    哪本书?请扔了。c++标准规定,函数参数的计算顺序是unsequenced。
    Value computations and side effects associated with different argument expressions are unsequenced.
    c++又规定,如果一个表达式中用到同一个变量,其中最少一个是写入,另外一个可以是写入或者读取,同时如果这2个变量的计算顺序是unsequenced,那么该表达式是undefined-behavior所以,这完全是个非法的c++程序。
      

  2.   

    ++k先运算
    k++后运算
    fun(k++,++k)相当于:
     a = k;
    b = k;a = k+1;
    fun(b,a);
    b = k+1;
      

  3.   

    你最好先去看看c++的运算那一章。起码简单的运算顺序还是要知道的。c的运算一般都是从右向左的。
    a++和++a一个是先赋值,再运算,一个是先运算,再赋值。