Tuesday, November 06, 2007

infront or infront of back

sounds crazy right, i could not come up with a sexy title for (pre or post increment operators in c), anyways today the issue of pre/post increment operators in c, sagar and i had a good 15 minute discussion how this works so he results are here

int i=5;
printf("%d,%d,%d",++i, i, i++);
/*
output: 7,7,5
*/

how, we understood that printf evaluates from right to left, so it'll do i++ first and return '5' and update value of i i.e. 6 in stack, the middle i is just i, the first ++i, will increment value of i in stack i.e. it becomes 7, now it'll examine the value of stack finds i=7, therefore it substitutes 7 as first and second argument


int i=5;
printf("%d,%d,%d",++i, i, ++i);
/*
output: 7,7,7
*/


how, we understood that printf evaluates from right to left, so it'll do ++i in stack i.e. 6 in stack, the middle i is just i, the first ++i, will increment value of i in stack i.e. it becomes 7, now it'll examine the value of stack finds i=7, therefore it substitutes 7 as first and second argument

because in post increment operator, the assignment happens before increment, therefore in case one 5 is assigned or returned, and get incremented on stack.
fair enough understanding i think.

refer:-

Blogged with Flock

1 comment:

Anonymous said...

Hey, the explanation is alright. But thats not a portable code, in fact C standard tells that result of such an expression in not defined. (go through sequence points concept in C standard)

You will see different results on different implementation (compiler) & OS's.