What happens when we use multiple assignments to the same variable within a single printf? Of course it is an unspecified behaviour. But how does gcc behave? (I hope the behaviour is independant of gcc version)
Examples:
int a=30;
printf("%d %d %d %d",a=12,a++,a=a+1);
The above code snippet gave output
12 31 12
a=30;
printf(" %d %d %d %d ",a--,a=12,a++,a=a+1);
gave output
12 11 31 11
a=30,b=100;
printf("%d %d %d %d %d %d %d %d ",a=12,b++,a++,a=200,b=20,a++,a=a+2,b=40);
gave output
12 20 200 12 21 32 12 21
a=30,b=100;
printf("<outside>(%d chars for inside printf) %d %d %d %d ",
printf("<inside> %d %d %d %d ",a=12,b++,a++,a=200),b=20,a++,a=a+2,b=40);
gave output
12 20 200 12 (22 chars for inside printf) 21 32 12 21
The explanation we found is evaluation is done right to left, assignments take final value of each variable and other expressions seem to be pushed to the stack? Is this a good explanation or is it something else going on there?
(NB: gcc may be using some registers instead of stack. But the behaviour seems same)
My teacher gave an explanation that there is a pipe for each variable and when %d flushes the pipe, its contents are not lost. So when again that variable is taken by another %d, the old content of the pipe is again used.
Notes: Pre-increment and Pre-decrement are treated like assignment whereas post-increment and post-decrement are treated like 'other expressions'.