Is something wrong with the compiler ?

Mark Brader msb at sq.sq.com
Wed Oct 3 04:52:49 AEST 1990


> > >         a = ( int )(( unsigned ) ( a = ~0 ) >> 1 ));
> > Sure you know what the results should be?  The ... expression is
> > assigning to `a' twice, which has unpredictable effects.

> Hmm, I thought it was ok -- doesn't "=" serve as a "sequence point" or
> some such thing, and since the lhs of the outer = is so simple it can't
> be "evaluated" before the rhs has been, and the rhs contains the other
> =, one is guaranteed the latter = is performed before the former, right?

Wrong.  First, assignment does not cause a sequence point.  The only
sequence points are:

        [1] After evaluating an expression that is not part of another
            expression; for instance, after an expression statement or
            after any one of the expressions in a for-header.

        [2] After evaluating the first operand of one of the operators
            "?"/":", "&&", "||", "," (conditional expression, logical
            and/or, or comma).

        [3] After evaluating the arguments of a function and before
            calling the function.  (Note that the comma between the
            arguments is not a comma operator, so the arguments may
            be evaluated in any order, and had better not alter the
            same variable more than once.

Second, even if the rhs did have to be evaluated first, this would not
imply that *side-effects* of its evaluation would be executed before
the next sequence point.  The compiler is free to interpret

           a = ( int )(( unsigned ) ( a = ~0 ) >> 1 ));

as if it was written

           a = ( int )(( unsigned ) ( tmpa = ~0 ) >> 1 ));
           a = tmpa;

(where tmpa is an otherwise unused variable of the same type as a).

Note incidentally that statements like

           p = p->f = newp;
and
           p->f = p = newp;

have undefined effect for the same reason.  If you find yourself writing
something like this, you should break it up into two statements.
-- 
Mark Brader		     "It is impractical for the standard to attempt to
SoftQuad Inc., Toronto	      constrain the behavior of code that does not obey
utzoo!sq!msb, msb at sq.com      the constraints of the standard."  -- Doug Gwyn

This article is in the public domain.



More information about the Comp.lang.c mailing list