Re: Accessing result of assignment

From: Michael Wojcik (mwojcik_at_newsguy.com)
Date: 09/10/04


Date: 10 Sep 2004 13:28:36 GMT


In article <843a4f78.0409100326.41d984ba@posting.google.com>, oldwolf@inspire.net.nz (Old Wolf) writes:
>
> int c;
> memset(x, c = 0, sizeof x);

That looks OK to me. N869 6.5.16p4 says that accessing the result of
the assignment operator *after the next sequence point* causes UB;
that's what made

   if ((a=b) == f(c))

undefined (because there's a sequence point after the arguments to f
are evaluated). In your example, the result of the assignment
operator (in "c = 0") is accessed before the sequence point that
occurs when all of memset's arguments have been evaluated, because
accessing it is part of evaluating memset's arguments; hence no UB.

So, curiously enough,

   if ((a=b) == c)

is legal, but eg

   if ((a=b) == (c,d))

is not, because of the sequence point caused by evaluating the first
operand of the comma operator.

OK, now someone should point out where I got it wrong...

(I'm glad Mark re-posted his question. This was a tricky one, and
I certainly hadn't noticed it before.)

-- 
Michael Wojcik                  michael.wojcik@microfocus.com
The lark is exclusively a Soviet bird.  The lark does not like the
other countries, and lets its harmonious song be heard only over the
fields made fertile by the collective labor of the citizens of the
happy land of the Soviets.  -- D. Bleiman


Relevant Pages

  • Re: x=(x=5,11)
    ... Evaluating an assignment operator causes ... seem to be saying that the sequence point after c but before d means ... that all the side effects of evaluating b will have completed. ... Memory that requires an erase before write is the most realistic example ...
    (comp.lang.c)
  • Re: why is it so ?
    ... > between evaluating `++i' and starting to execute `f', ... > I don't think this guarantees a sequence point between the ... "it stands to reason" that the assignment cannot ... What if the compiler can predict the ...
    (comp.lang.c)
  • Re: Question regarding the short circuit behavior
    ... evaluating one expression only in sequence point. ... the actual increment of the object can happen ... but can actually crash in reasonable situations. ...
    (comp.lang.c)
  • Re: Sequence point and +=
    ... Store the result of RHS in LHS. ... Is RHS guaranteed to be evaluated before LHS? ... point after evaluating RHS and before evaluating LHS? ... No. C99 page 437, Annex C, Sequence points: ...
    (comp.std.c)
  • Re: Sequence points and function calls.
    ... So by my reading there is no undefined behaviour and i will ... > There are indeed two sequence points in the above statement. ... But not before evaluating the arguments to the function, ... Or unless the compiler is broken. ...
    (comp.std.c)

Loading