int i,j;
i = j = 5;
j = i++ + (i*10);
cout<<i<<" "<< j <<" "<<i++;The above code is giving two different output in C++14 and C++17.Can anyone explain why?? In c++14 its showing 7 65 6 In C++17 its showing 6 65 6
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3676 |
| 2 | Kevin114514 | 3659 |
| 3 | jiangly | 3640 |
| 4 | turmax | 3450 |
| 5 | tourist | 3382 |
| 6 | strapple | 3360 |
| 7 | Um_nik | 3354 |
| 8 | squareOf105 | 3348 |
| 9 | maroonrk | 3312 |
| 10 | idontwannadothis…e | 3191 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 156 |
| 2 | nik_exists | 151 |
| 3 | maspy | 149 |
| 4 | AmShZ | 145 |
| 5 | Um_nik | 143 |
| 6 | Errichto | 139 |
| 7 | BledDest | 136 |
| 8 | adamant | 135 |
| 9 | maroonrk | 132 |
| 10 | cry | 130 |
int i,j;
i = j = 5;
j = i++ + (i*10);
cout<<i<<" "<< j <<" "<<i++;The above code is giving two different output in C++14 and C++17.Can anyone explain why?? In c++14 its showing 7 65 6 In C++17 its showing 6 65 6
| Name |
|---|



Perks of undefined behaviour.
First of all
operator<<is just a function. So the last line could be translated into :operator<<( operator<<( operator<<( cout, i ), j ), i++ );for simplicity let's replace
operator<<withff(f(f(cout, i), j), i++)In C++ order of evaluation of function arguments is unspecified. So it is not guaranteed to get executed from left to right. That's why in my computer with my compiler it gives 6 65 6 regarding any standard.
In your case, at first
i++is evaluated which incrementsibut returns previous value ofi. So the firsti = 7and the lasti = 6.Conclusion :
DON'T RELY ON ORDER OF EVALUATION OF FUNCTION ARGUMENTScoutis an object.operator<<is a function.Also I want to add, that the same goes for
operator+, etc. Thusi++ + (i*10)has an undefined behavior, too. It's the same asoperator+(i++, operator*(i, 10))Yep! my bad. fixed, thanks!
no u
Thank you...It was really helpful. Had no idea about this .
It's possible that running this code will trigger a world war, the C++ standard allows that.
Btw, I'm curious, does the C++ standard somehow imply that other code constructions with defined behavior don't trigger a world war? :)
Well, running well defined code cannot directly start a world war. However, if the code running has any observable side effects, that may contribute.