Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
#include<stdio.h>
main()
{
      int i=5;
      printf("%d",++i + ++i + ++i);
}


Can anyone tell me how this prints 22..??
Posted

It first evaluates ++i + ++i, the unexpected result is 14, because the operation is i + i, but before doing this it is incremented. The result is saved to some place, for instance the registry, and after that i is incremented one more time and added to the saved result.

Even this may give 24, because of i + i + i. First is evaluated ++i, after that it is evaluated again and again. And after that is done operation result = i + i + i
 
Share this answer
 
Comments
skrtbhtngr 30-Nov-12 6:50am    
#include <stdio.h>
void main()
{
int a=5, x;
x=++a + ++a + ++a;
printf("%d",x);
}
If I use this code, it prints 24...!! (Visual Studio 2010)
It's all down to the order in which the compiler generates the code. In general this sort of construct should never be used in live code as it is prone to giving the wrong result. Step through the generated assembler code with your debugger to see what is happening.
 
Share this answer
 
Comments
[no name] 29-Nov-12 23:06pm    
Yes Richard you are correct..My vote is 5
The GCC compiler with the -Wall switch, gives the following warnings:
j.c:5: warning: operation on ‘i’ may be undefined
j.c:5: warning: operation on ‘i’ may be undefined


Why the operation might be undefined is well explained at Stack Overflow: printf and ++ operator [closed][^].
 
Share this answer
 
I agree with Richard. Because in live project this kind of code will never used. This may give unexpected result. yes, this is very confusing. But compiler seeing this code section as it's own way. ie, it first evaluate
i = 5;
(++i) = 6. hope you got it.
but, next it take another two + operator as postfix ie, i++. hence now i have value 7. ie
1) ++i
2)i++
current i = 7.
then it take next + operator for addition. ie (i++) + i = 14. ok.
then compliler take i++. hence i have now value 15. next compliler take previous i result( it is stored in registry) and it to current result 15 + 7 = 22.
you can ensuare it using assembly debugging.

Note : Please avoid using of this kind of coding standard.
 
Share this answer
 
Is it print 22 really?! Ok,have a look here..
At First,you declared i as int and assign 5 to it.
so at first time ++i will be 6(i+1)
at 2nd time ++i will be 7(i+1)
at 3rd time ++i will be 8(i+1)
So now sums up all those 3,(6+7+8)=21
For my case,it prints 21.
 
Share this answer
 
Comments
[no name] 30-Nov-12 0:12am    
Yeah I also got 21...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900