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

By -
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...!!

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

  1. 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 ..!!

  2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *