首页 > 试题广场 >

阅读C++语言代码输出() int main() { &

[单选题]
阅读C++语言代码输出()
int main()
{
    int arr[]={1,2,3,4,5,6,7};
    int *p=arr;
    *(p++)+=89;
    printf("%d,%d\n",*p,*(++p));
    return 0;
}

  • 3 3
  • 2 2
  • 2 3
  • 3 2
这题明显有问题啊,在primer里就讲到在同一条语句里执行p和p++操作得到的是未定义的值,在我MAC上跑就是2,3在window下就是3,3。讲道理没意义这题
发表于 2019-10-22 21:02:47 回复(1)
参数的传递压栈顺序总是从右到左的,即对于函数
void __stdcall swap(int& a,int& b) { int c = a;
  a = b;
  b = c;
}
其伪代码执行过程如下:
push b; //先压入参数b push a; //再压入参数a call swap; //调用swap函数
故 printf("%d,%d\n",*p,*(++p)); 中,第四个参数*(++p)会被先执行,此时p已经指向了3,然后执行第三个参数*p的压栈过程时,p已经指向了3,故结果为3,3

参考文章《压栈,跳转,执行,返回:从汇编看函数调用》2.3.1 :https://www.jianshu.com/p/594357dff57e


发表于 2018-11-13 11:28:04 回复(0)