Sunday, August 19, 2007

printf statement

printf statement plays lot of tricks with those who are always new to the C programming language. Consider the following statement which I was informed when I was doing my second semester
int i=5;

printf(”%d %d %d”,i,++i,i++);

The output predicted by most of the students is usually 5 6 6. But this is not the actual output for this statement. The printf statement usually is handled by the compiler from right side to left side. So it starts from i++ first. Here the initial value of i is 5. So when it reaches i++ statement the value remains the same (its a post increment) and the next step is ++i which is pre increment step and the value of i becomes 7 (coz the i++ increments the value of i after it reaches the next step i.e. ++i). So the final value of i is 7 here.

But while printing the printf statement executes in the normal fashion as we expect it to execute. So it prints the value of i first followed by ++i and finally i++. So the actual output for this statement is 7 7 5.

For those who know this please dont mind about this post. For those who dont know this hope you find it useful (though mostly all will be knowing it ;) But still many dont know this coz I’ve asked many about this and many still struggle in this).

I’ll ask an important question in the next post which i think many C program lovers will like.

Cheers!!!!

No comments: