+ 5

#include <iostream> using namespace std; int main() { int a=10,b; b=++a+(++a); cout<<b; return 0; }

why I am getting 24 as a output please help thanks..

28th Aug 2017, 1:07 PM
Rishabh Rai
Rishabh Rai - avatar
9 Respuestas
+ 2
Yesterday, i posted same question like this. int a=5,b=0; b=++a + ++a + ++a; cout<<b; The output is 22. Here's my explanation. First of all we divide the expression in 3 parts ++a each. When first ++a is performed the value of "a" becomes 6, but it's not stored into stack, when second parts is performed the values becomes 7.This time addition of both is performed, but as the value of a is 7, the values stored into stack are 7,7. Now the last part is evaluated & the value of "a" becomes 8 & as there is addition to be performed, it is stored into stack. So the contents of stack are 7,7,8. By performing addition of them answer comes out to be 7+7+8=22. When we use "volatile int", each time when value of "a" increments, it's stored into the stack. So the stack content in this case is 6,7,8 & answer comes out to be 6+7+8=21. Note that the logic is followed in GCC platform. If you're using Turbo C, then you will get the answer as 24. In this case stack contents are same as last value i.e. 8,8,8.🙂
29th Aug 2017, 2:04 PM
Nainish kher
Nainish kher - avatar
28th Aug 2017, 1:32 PM
Mattéo
+ 3
No problem bro✌
29th Aug 2017, 3:08 PM
Nainish kher
Nainish kher - avatar
+ 2
because of the use of non volatile int. change the line to- volatile int a=10, b; to get the desired output.
28th Aug 2017, 1:24 PM
Mohd Zaid
Mohd Zaid - avatar
+ 2
can we use volatile keyword in C language also..
28th Aug 2017, 1:28 PM
Rishabh Rai
Rishabh Rai - avatar
+ 2
thanks
28th Aug 2017, 1:32 PM
Rishabh Rai
Rishabh Rai - avatar
+ 2
For a better understanding see this code- https://code.sololearn.com/ctog8Gtjyt0f/?ref=app
28th Aug 2017, 1:34 PM
Mohd Zaid
Mohd Zaid - avatar
+ 1
Yes
28th Aug 2017, 1:31 PM
Mohd Zaid
Mohd Zaid - avatar
+ 1
thanks bro it really helped I was confused..
29th Aug 2017, 3:04 PM
Rishabh Rai
Rishabh Rai - avatar