Search code examples
cpost-incrementpre-increment

Is this an undefined behavior in C?


I am running my C code on gcc to understand pre/post increment operator. However the results that I see are not what I expected. Like for the line 6, since i is 5, it should have been

8 7 6 5 5

But it is 8 7 6 5 8

Then coming to the last line, it displays 14 14 14 14. Can someone please explain this behavior. I had expected 14 14 13 12

Is this compiler dependent? Is the beahviour of printf function on sequence points undefined?

#include <stdio.h>

int main()
{
        i = 5;
        printf("%d %d %d %d %d \n", i, i++, i++, i++, i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d %d %d %d \n", i, ++i, ++i, ++i);

}

Solution

  • The Standard states that

    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.

    And these are the places where you will find sequence points:

    • at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression);

    • at the ||, &&, ?: and comma operators; and

    • at a function call (after the evaluation of all the arguments, and just before the actual call).

    An elaboration of the last point: the comma operators in a function call are not sequence points and the expressions between the ,s can be evaluated in any arbitrary order.

    Check this and this for better understanding.

    In printf("%d %d %d %d %d \n", i, i++, i++, i++, i);, you are writing to the same memory location more than once between two sequence points, thus invoking undefined behaviour.