C sequence points

Olve Maudal and I created a Deep C/C++ slide-deck recently. It's been downloaded over 500,000 times indicating no small appetite for learning some of the deep secrets of C and C++. So...




In this C fragment z is initialized to the value of n after n += 42 takes place.
if (n += 42)
{
    int z = n;
    ...
}

But how do you know this? For sure? The answer is perhaps not as obvious as you might think. The C standard says:

5.1.2.3 Program execution
(paragraph 2)
Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.

In C parlance, n is an object, and n += 42 modifies n. So n += 42 is a side effect. The only thing governing the sequencing of side-effects are sequence points. And there are a lot less sequence points in C and C++ code that you might imagine. There is a sequence point between n += 42 and the initialization of z. But where? And why? The standard says:

6.8 Statements and blocks
(paragraph 4)
A full expression is an expression that is not part of another expression or of a declarator. ... The end of a full expression is a sequence point.

and:

6.8.4 Selection statements
Syntax
  selection-statement:
     if ( expression ) statement

If we lexically enlarge the expression n += 42 to its left or right we hit the parentheses that form part of the if statement. In other words, the expression stops being an expression and starts to become a statement. That means n += 42 in the fragment is a full expression. That's why there's a sequence point at the end of n += 42. In pseudo code it looks like this:
n += 42;
sequence-point
if n != 0 goto __false__;
int z = n;
...
__false__: 

Photo: http://www.noaanews.noaa.gov/stories2005/images/rov-hercules-titanic.jpg


1 comment:

  1. http://clanguagestuff.blogspot.in/search/label/sequence%20points

    ReplyDelete