*p++ = *p and more

Gregory Smith greg at utcsri.UUCP
Sun Apr 6 08:28:54 AEST 1986


In article <1771 at ihlpg.UUCP> tainter at ihlpg.UUCP (Tainter) writes:
>> I think compilers can do the post-increment anytime they feel like it
>> with in the statement.     The semantics of a[i] = b[i++];   isn't
>> defined so the compiler can do whatever it wants.  Even if that means
>> that both i's are evaluated before the increment is done.
>> Bill Smith
>> ihnp4!uiucdcs!wsmith
>
>According to K&R page 42 section 2.8
>     ....But the  expression ++n increments n 'before' using its value, while
>     n++ increments n after its value has been used.
>
>SO any time they feel like it is not valid.  Indexing a[i] first or
>indexing b[i] first IS valid, but b is indexed with the value of i BEFORE
>i is incremented.  a can be index either before or after i is incremented.
>--j.a.tainter
b is indexed with ( the value of i BEFORE i is incremented ):	True
(b is indexed with the value of i ) BEFORE i is incremented:	False

This compiler *can* increment i before doing anything anything else; as
long as the *original* value of i is used.  This is why there are
quotes around 'before' in your quote from K&R.  I have an ( admittedly
brain-damaged ) C compiler for 8080 that *always* does i++ as (++i-1).
Here is a horribly contrived example where it makes a difference:

register struct { int wombat } *p,*q;

		*q = p[(p++)->wombat ];

If the increment is done after the indexing, as you say, this will be
the same address as p[p->wombat]; if the increment is done as (++p-1),
and p[..] uses the incremented value of p, then (p+1)[p->wombat] will
result. Actually, p++ need not be done as (++p-1) for this to happen.
In fact, it will only work as you say if the first 'p' mentioned is
used unincremented, which is unlikely if p is a register. I realize that
I have an operation (->, between p++ and []) that b[i++] doesn't have; the
point still stands.

The point is that there is no guarantee as to when the increment is
done in an expression like the one above. All you know is that p++ will
return the original value of p ( in my example ).
-- 
"If you aren't making any mistakes, you aren't doing anything".
----------------------------------------------------------------------
Greg Smith     University of Toronto      UUCP: ..utzoo!utcsri!greg



More information about the Comp.lang.c mailing list