Total Pageviews

Thursday, November 17, 2011

C loves me...C loves me not...

Hi C programmers, i got stuck at this piece of code and concept of precedence, associativity and order of evaluation within printf() in C.Most of you are adept C programmers.So please, you gotta help me out in explaining the output of this code.This post may clarify some of your queries as well as unary operators are very important.

#include <stdio.h>
void main()
{
 int j = 1;

printf("%d%d%d%d" ,++j,j++,j,--j);

}
 Output is 2022
but as my friends and I thought, it should be 2020 if we consider the order of evaluation to be R to L.
Please reply to this post if you find a possible explanation to it.

4 comments:

  1. Whenever a variable is changed and assigned to itself, then its behavior in an expression is not defined. So different compilers would generate different outputs.

    ReplyDelete
  2. I tried in codepad.org...can u try and do it in some other and verify that it gives different results for different compilers like mayb putty or linux...i have neither of them for now...

    ReplyDelete
  3. According to ANSI C standard the order in which function arguments are evaluated is not defined.So, yeah the R-L evaluation does not hold true too.Try a= 1,printf("%d %d %d",a,a++,a)!

    ReplyDelete
  4. you are possibly correct if you are confirming it from ANSI C standards...thanks!! :)

    ReplyDelete