Search code examples
cundefined-behavior

C programming language Undefined behavior


I am following book which is about C programming language. The book name is Programming with C and C++ and this book is written by Devendra Naga.

I didn't understand the explanation of code snippet.

enter image description here

Why is this code output undefined behavior?. I know that white space characters ignore by the compiler. Could you please illumate me about explanation behavior of this code ? Book writer is says output of this code is undefined bahvior but I am not sure about it. Maybe it is related the sequence point. But I am not sure.

I think this code does not contain any undefined behavior situation.


Solution

  • On Section 6.5.2.4 Paragraph 2 of "latest freely available draft of C17 standard",

    The result of the postfix++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

    The value computation of the result is sequenced before the side effect of updating the stored value of the operand.

    So behavior of postfix++ seems well defined.

    Maybe author tried to explain about possible undefined behavior on multiple unsequenced side effects on one scalar value, but failed horribly.

    On Section 6.5 Paragraph 2,

    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.

    making result of things like printf("%d %d\n", i++, i++); undefined.

    Don't blame me about using draft instead of published standard. You need to pay 216 Swiss Francs to get one PDF copy of it.