简体   繁体   中英

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. Here my doubt is **p is pointing to x only which is incremented by second operand ++(**p). so value of y should be 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) .

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. However, on your compiler, it seems that the LHS is evaluated first.

From the cppreference site linked in the comments by 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++….

PS: Interestingly, changing to y = ++(**p) + **p; also gives 6 6 6 12 as the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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