简体   繁体   English

以下程序的意外输出

[英]unexpected output of the following program

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{

     int y,**p,*pt;
     int x=5;
     pt=&x;
     p=&pt;
     y=**p + ++(**p);
     cout<<*pt<<" "<<**p<<" "<<x<<" "<<y;
     getch();
     return(0);
}

output generated 6 6 6 11, why not 6 6 6 12 kindly guide on execution step. 输出生成的6 6 6 11,为什么不是6 6 6 12请在执行步骤中进行指导。 Here my doubt is **p is pointing to x only which is incremented by second operand ++(**p). 在这里,我的疑问是** p仅指向x,第二个操作数++(** p)将其递增。 so value of y should be 12. 因此y的值应为12。

This is classic undefined behaviour ! 这是经典的未定义行为 There is no guarantee in the C++ standard about the order of evaluation of the operands of the + operator in y=**p + ++(**p) . C++标准中,不能保证y=**p + ++(**p) +运算符的操作数的求值顺序。

I tested your code in MSVC and clang-cl and I get the output: 6 6 6 12 - which suggests (as you expect) that ++(**p) is evaluated first. 我在MSVCclang-cl测试了您的代码,然后得到了输出: 6 6 6 12这表明(如您所愿)首先对++(**p)进行了评估。 However, on your compiler, it seems that the LHS is evaluated first. 但是,在您的编译器上,似乎首先评估了LHS。

From the cppreference site linked in the comments by Scheff : 从ceffreference网站链接到Scheff的评论中:

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). 未指定任何表达式的任何部分的评估顺序,包括函数参数的评估顺序(以下列出了一些例外)。 The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again. 编译器可以按任何顺序求值操作数和其他子表达式,并且在再次求同一个表达式时可以选择其他顺序。 There is no concept of left-to-right or right-to-left evaluation in C++…. 在C ++中没有从左到右或从右到左求值的概念。

PS: Interestingly, changing to y = ++(**p) + **p; PS:有趣的是,更改为y = ++(**p) + **p; also gives 6 6 6 12 as the output. 还给出6 6 6 12作为输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM