p[1] vs. *(p+1)

Mark A Terribile mat at mole-end.UUCP
Tue Sep 4 08:02:02 AEST 1990


In article <1745 at io.UUCP>, prs at io.UUCP (Paul Schmidt) writes:
> In article <26D952F5.4E44 at tct.uucp> chip at tct.uucp (Chip Salzenberg) writes:
> >
> >Any compiler that considers "*(p+1)" and "p[1]" to be different does
> >not comply with the ANSI standard -- or with K&R, for that matter.
 
 
> So, that means that the compiler must know the size of the elements of
> array p, and that *(p+1) does not add 1 to p, but instead adds
> sizeof(array_element_type) to p?

What's the problem?  The compiler needs to know the length anyway.  And yes,
the pointer is adjusted by the length of the object at which it (is presumed
to) point.
 
> I must confess that I use p[1] in these cases, and count on the compiler
> to optimize for me.

What does optimization have to do with anything?  The compiler can generate
the same code for both expressions.  Because C gives the programmer so much
addressing control and because aliasing can occur, the compiler cannot
always do strength reductions.

The equivalence of  p[ i ]  and  *( p + i )  is at the very heart of the C
language definition.  If you are programming in C, you CAN rely upon it,
not by some coincidence or compiler peculiarity, but in the most portable
way of all, by the actual definition of the language.  If the compiler
writer cannot implement this behavior well, he cannot implement C well on
that machine.
-- 

 (This man's opinions are his own.)
 From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list