Another silly question

Mark A Terribile mat at mole-end.UUCP
Fri May 19 15:34:47 AEST 1989


> > Ok, folks.  In regards to  "a[i] == *(a+i) == *(i+a) == i[a]", let me
> > refer to the oft-used example  2["hello"].

> > I agree that this works and is equivalent to "hello"[2].  I've seen it
> > in books and postings.  My simple question is why? 

For the reason that everyone has said:  x [ y ]  IS DEFINED AS  *( x + y )

and if one expression is legal, so is the other one.
 
> 	The supposed proof of a[i] == i[a] rests on the faulty
> 	assumption that (x+y) == (y+x) in all contexts; this is
> 	not correct.

Are you saying that  2[ "hello" ]  is not the same as  "hello"[ 2 ] ?  If
so, you are wrong.  The ordering of the operands does not matter.  C has
been this way from about the beginning and unless there is a specific item
in the pANSI spec (I find none in K&R-II) it is allowed.  (But see K&R-II,
section A8.6.2: ``Therefore, despite its asymmetric appearance, subscripting
is a commutative operation.'')
 
> 	When "+" denotes simple (ie int/float/etc) arithmetic, the
> 	operation commutes; when it denotes pointer arithmetic,
> 	commutation is not legal/meaningful.

It is.  Using K&R-II again, over and over in discussing the addition of an
integer to a pointer, they say ``one operand ... and the other operand ...''
*Never* are the first and second operands distinguished.  There is a reason for
this care.

> 	The statement that *(a+i) == *(i+a) is therefore invalid.

Not only

		*(a+i) == *(i+a)

for  a  of any pointer type (excluding pointer-to-function) and  i  of an
integral type, but

		*( a + i ) === * ( i + a )
		( a + i ) ==  ( i + a )
		*( a + i ) == * ( i + a )

etc.

If your compiler rejects  "hello"[ 2 ]  it is broken.  (Have you tried it, by
the way?)
-- 

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



More information about the Comp.lang.c mailing list