Re: Does this cause undefined behaviour?

From: Jack Klein (jackklein_at_spamcop.net)
Date: 12/31/03


Date: Wed, 31 Dec 2003 20:48:44 GMT

On Wed, 31 Dec 2003 18:35:22 +0000, Thomas Stegen
<tstegen@cis.strath.ac.uk> wrote in comp.lang.c:

> Jack Klein wrote:
>
> > On Wed, 31 Dec 2003 15:34:22 +0000, Thomas Stegen
> > <tstegen@cis.strath.ac.uk> wrote in comp.lang.c:
> >
> >
> >>Martin Dickopp wrote:
> >>
> >>> (1) The value of the object may be modified at most once.
> >>> (2) If the value of the object is modified at all, the previous value
> >>> may be used only to determine the new value.
> [snip]
> >>What about
> >> a[++i] = i;
> [snip]
>
>
> > Nope, absolutely undefined,
>
> I think it is undefined too.
>
> > per Martin's #2 above.
>
> But I am not sure this is the reason. Because it is the prior value
> that cannot be read for other reasons than determining the new value.
>
> > The RHS of the
> > assignment reads the value of i outside of the expression on the LHS
> > that uses it to compute the new value.
>
> The value assigned is not necessarily the prior value, is my point.
> This value is probably undefined though, since it only needs to be
> incremented before the next sequence point.
>
> My point is that the above is undefined, but I am not sure if it is
> 6.5#2 (C99) that is the clause that causes this.

That's exactly the point of the wording from the standard, this is an
EXACT quote from paragraph 2 of section 6.5 of the C standard:

========
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.
========

Note the second sentence.

Now in the expression under discussion:

    a[++i] = i;

The read of the value 'i' on the left hand side is perfectly proper,
it is used in the computation of the new value. The read of the value
of 'i' on the right hand side causes undefined behavior because it is
not involved in the calculation of the value finally assigned to 'i'.

Unless you can contend that the RHS of the expression does not need to
perform an lvalue-to-rvalue conversion, that is read the value of 'i',
and I don't think you are doing so.

-- 
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq