+ 5

Can anyone explain the output of this code?

#include <stdio.h> void main() { int i=4, x; x= ++i + ++i + ++i; printf("%d",x); } //Output: 19

3rd Apr 2018, 6:03 PM
Md. Asiful Hoque Prodhan
Md. Asiful Hoque Prodhan - avatar
9 odpowiedzi
+ 1
Frank, yup, it works
4th Apr 2018, 6:44 AM
Ali Zhussupov
Ali Zhussupov - avatar
+ 1
++i increments i once though sneeze. How do you explain the double increment? Thanks.
4th Apr 2018, 8:51 AM
Emma
+ 1
The double increment the compiler sees 3 statements ++i + ++i A C B statement A : ++i now i is 5 the compile goes on with statement B : since i is already 5, ++i makes 6 but since i is the same variable also the first i is 6 statement C : 6 + 6 = 12
4th Apr 2018, 8:56 AM
sneeze
sneeze - avatar
+ 1
Thanks sneeze
4th Apr 2018, 8:59 AM
Emma
0
As far as i know, behavior of such expressions in C++ is not defined. In this case, i guess, its 6 + 6 + 7.
3rd Apr 2018, 6:37 PM
Ali Zhussupov
Ali Zhussupov - avatar
0
first - i dont do c++ but in my eyes,... is this code really works?
4th Apr 2018, 6:35 AM
Frank Hehner
Frank Hehner - avatar
0
TheEpicWobbuffe, the same goes for C (undefined behavior)
4th Apr 2018, 6:44 AM
Ali Zhussupov
Ali Zhussupov - avatar
0
Yes it works but the behaviour is undefined. So it is really bad practice to code like this. If this is a challenge question please report it. In my opnion this is not something that should be promoted. What happens x = ++i //increment i twice make i= 6 x = ++i + ++i //read 6 + 6 makes 12 x = 12 + ++i// read 12 + 7 makes 19 https://code.sololearn.com/ci36tO6Sgds0
4th Apr 2018, 8:42 AM
sneeze
sneeze - avatar
- 1
I don't do C++.
3rd Apr 2018, 9:08 PM
TheEpicWobbuffe
TheEpicWobbuffe - avatar