Search code examples
clanguage-lawyerstandardsundefined-behavior

Compiler dependency and well defined output


Is the output of this code well defined ? I thought that it is updating the variable more than once between two successive sequence points.

#include<stdio.h>

int main()
{
 int p=10,*q;
 q= &p;
 *q=p+++*q;
 printf("%d",*q);
 return 0;
}

Solution

  • This code exhibits undefined behavior.

    Section 6.5p2 of the C standard states:

    If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings

    Because q contains the address of p, the expression *q=p+++*q; is writing p twice (once with the postincrement operator directly on p and once when assigning to *q) without an intervening sequence point or other sequenced operations. This violates the above clause disallowing more than one unsequenced side effect on an object.