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 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | atcoder_official | 162 |
3 | maomao90 | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | djm03178 | 152 |
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<<
withf
f(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 incrementsi
but returns previous value ofi
. So the firsti = 7
and the lasti = 6
.Conclusion :
DON'T RELY ON ORDER OF EVALUATION OF FUNCTION ARGUMENTS
cout
is 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.