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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 151 |
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.