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
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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
Название |
---|
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.