#include<stdio.h>
void main()
{
int a=10;
printf("%d %d %d",a,++a,++a);
}
Can anybody tell me why the output of this code is 12 12 12 and not 12 12 11???
I compiled it on TDM-GCC 4.7.1
#include<stdio.h>
void main()
{
int a=10;
printf("%d %d %d",a,a++,a++);
}
Because the output of this is 12 11 10
Behavior in such cases is undefined afaik
although in general this type of construction is something to be avoided, I notice you can get the behavior you expect (gcc 4.5.3) by declaring
volatile int a=10;
which forces the compiler to treat a variable as if it were memory mapped IO
see also http://stackoverflow.com/questions/17907520/evaluation-order-of-increment-operations-in-c
Pre increment (++a) always gets evaluated before anything else gets executed on that line.
Hence, value of variable a got incremented twice before executing printf statement.
a,++a,++a code first solve left to right than variable a value increment two times than a=12
after that a=12 assign all 3 a variable right to left so all a print 12,12,12
That’s fine. But why is the last output incremented twice?? second and first place I get 12 that’s pretty cool. Turbo c gave me proper answer 12 12 11.
I got it…! Superb… Thnx a lot…!!!