C Programming FAQs: Frequently Asked Questions

Category: Programming
Author: Steve Summit
4.2
This Month Stack Overflow 1

Comments

by anonymous   2019-01-13

A good explanation about what happens in this kind of computation is provided in the document n1188 from the ISO W14 site.

I explain the ideas.

The main rule from the standard ISO 9899 that applies in this situation is 6.5p2.

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 read only to determine the value to be stored.

The sequence points in an expression like i=i++ are before i= and after i++.

In the paper that I quoted above it is explained that you can figure out the program as being formed by small boxes, each box containing the instructions between 2 consecutive sequence points. The sequence points are defined in annex C of the standard, in the case of i=i++ there are 2 sequence points that delimit a full-expression. Such an expression is syntactically equivalent with an entry of expression-statement in the Backus-Naur form of the grammar (a grammar is provided in annex A of the Standard).

So the order of instructions inside a box has no clear order.

i=i++

can be interpreted as

tmp = i
i=i+1
i = tmp

or as

tmp = i
i = tmp
i=i+1

because both all these forms to interpret the code i=i++ are valid and because both generate different answers, the behavior is undefined.

So a sequence point can be seen by the beginning and the end of each box that composes the program [the boxes are atomic units in C] and inside a box the order of instructions is not defined in all cases. Changing that order one can change the result sometimes.

EDIT:

Other good source for explaining such ambiguities are the entries from c-faq site (also published as a book) , namely here and here and here .