| • Science | • People | • Locations | • Timeline |
For example,
int i, j; i = 1; j = i;since the ";" after the second line is marks a sequence point, i is guaranteed to have '1' in it, and so j will be correctly populated.
If, however, we have
int i = 1; i = i++;then while the expression on the right hand side is indeed guaranteed to be 1, the side effect of the increment (++) operator, of actually incrementing the variable to 2 is need not be executed until the next sequence point. This also goes for the assignment (=) operator. As a result, it is not guaranteed whether the = or ++ will have its side effect happen last, and therefore whether i will end up 1 or 2. In C, having two side effects without an intervening sequence point is undefined behaviour, and any result may arise. Thus, the above code may generate any value for i or even perform unrelated actions (an unlikely scenario). A statement like i = ++i;, in which it seems the ++ must be evaluated before the =, still breaks the sequence point rule and has undefined behavior.
In C, function calls, &&, ||, the comma operator, and ; are among sequence points. Commas that separate parameters to function calls are not.
Computer science