How post-increment & pre-increment both are evaluated in function argument?

While surfing internet i came to following scenario. The behavior of bellow’s function i can not understand .Can you know why this output comes ?

   int main() {
   int a=5;
   printf("%d %d %d",a++,a++,++a);
   return 0;

the output of this program is like

 7 6 8


hey friends i have completed my B.Tech in CE from Ganpat University & now i am working as Android Middleware & Application Developer in one Private firm. i really enjoy programming...!!

More Posts - Facebook

3 Comments to “How post-increment & pre-increment both are evaluated in function argument?”

  • jigar September 27, 2011 at 9:30 am

    compile it with gcc -Wall filename.c

    compiler will give warning as its undefined behaviour. for operation on a.

    output of this program will differ on different system ..!!

    • saurabh September 27, 2011 at 9:49 am

      but how differ?? what is the logic behind this on Linux

  • jigar September 27, 2011 at 10:05 am

    As per c standard

    “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.”

    There is a sequence point before evaluating the arguments to a function, and a sequence point after all the arguments have been evaluated (but the function not yet called). Between those two (i.e., while the arguments are being evaluated) there is not a sequence point (unless an argument is an expression includes one internally, such as using the && || or , operator).

    That means the call to printf is reading the prior value both to determine the value being stored (i.e., the a++) and to determine the value of the second argument (i.e., the a++) and also 3rd argument (i.e the ++a). This clearly violates the requirement quoted above, resulting in undefined behavior.

Post comment

Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

Find us on Facebook

Find us on stackoverflow


Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link