why the result is 43 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

why the result is 43

#include <iostream> using namespace std; int main() { int i=2; i+=4; i--; cout <<i--<<--i; return 0; } //Like it if u love it

6th Feb 2017, 8:59 PM
L Boudhar
L Boudhar - avatar
10 Answers
+ 14
this is just undefined behaviour, no need to worry, try in another compiler and u will get a different surprise
7th Feb 2017, 2:46 AM
‎‏‎‏‎Kueen
‎‏‎‏‎Kueen - avatar
+ 8
Guess what. If you do this: int i=2; i+=4; i--; cout << i-- << i--; Output would be 45. So yes, smells fishy.
7th Feb 2017, 12:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 8
"The order in which your x++ and ++x statements are evaluated is undefined, so is the effect of your code." Source: http://stackoverflow.com/a/33445861
7th Feb 2017, 12:20 AM
Jafca
Jafca - avatar
+ 4
,. cout<<i--<<--i as I understand it is two statements not one.. therefore it isnt undefined behaviour at all, it is behaving exactly as expected it is shorthand for cout << i--; cout << --i;
6th Feb 2017, 10:14 PM
jay
jay - avatar
+ 3
2+4=6 right... 6-1=5.. 5-1=4... 4-1=3.. you couted 4 and 3 to the same line with no spaces this displays them as 43 .. you could just ask about prefix and postfix operators or just google it...
6th Feb 2017, 9:47 PM
jay
jay - avatar
+ 3
Using more than one increment or decrement operator with cout in single line leads to undefined behavior. In you case, output is unexpected because order of evaluation of i-- and --i in single line is undefined.
6th Feb 2017, 10:00 PM
Yousaf
Yousaf - avatar
+ 3
@jay your answer is not correct. If it wasn't undefined beahvior, it should have printed 53 not 43. Maybe you also need to google postfix and prefix operators :p
6th Feb 2017, 10:04 PM
Yousaf
Yousaf - avatar
+ 3
@jay it is undefined behavior because as i explained in my answer, order of evaluation of decrement or increment operators used like this in single line is undefined. If it wasn't undefined, output should be 53 not 43.
6th Feb 2017, 10:25 PM
Yousaf
Yousaf - avatar
+ 2
output is 53
7th Feb 2017, 1:06 AM
Kawaii
Kawaii - avatar
+ 1
this is undefined behaviour. but for most compilers this undefined behaves like this. evaluate from right to left. also remember that prefix is lvalue. so it's value can be modified later too
7th Feb 2017, 3:13 AM
Chetan Dugar
Chetan Dugar - avatar