What is the output of following code? And why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the output of following code? And why?

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

28th Aug 2017, 10:20 AM
Nainish kher
Nainish kher - avatar
4 Answers
+ 2
Actually the answer is 22. I don't even get it.
28th Aug 2017, 11:13 AM
Nainish kher
Nainish kher - avatar
+ 2
it should be 21 but i got 22
28th Aug 2017, 12:46 PM
Sadegh
+ 2
This is perhaps Because of the Non-volatile int. It stores the variables into CPU Register hence giving the output 14 as after the '+' (arithmetic operator), all the remaining '++' are evaluated first because of the precedence system of C++. Hence the equation after the first '+' operator becomes '+8+8'. And the whole equation becomes '6+8+8'. Try Using Volatile int in place of int to solve the problem and get the answer '21' like this: volatile int a=5, b=0;
28th Aug 2017, 1:00 PM
Mohd Zaid
Mohd Zaid - avatar
+ 2
So guys, i finally get the answer. 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, 1:57 PM
Nainish kher
Nainish kher - avatar