[comp.lang.c] ai == ia

krazy@claris.com (Jeff Erickson) (05/19/89)

From article <2336@Portia.Stanford.EDU>, by mesmo@Portia.Stanford.EDU (Chris Johnson):
> From article <17812@cup.portal.com>, by Tim_CDC_Roberts@cup.portal.com:
>> 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? 
> 
> 	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.
> 
> 	When "+" denotes simple (ie int/float/etc) arithmetic, the
> 	operation commutes; when it denotes pointer arithmetic,
> 	commutation is not legal/meaningful.
> 
> 	The statement that *(a+i) == *(i+a) is therefore invalid.

You're wrong.  According to K&R2, page 205:

	"A pointer to an object and a value of any integral type may be
	added.  The latter is converted to an address offset by
	multiplying it by the size of the object to which the pointer
	points."

Nowhere does it mention or imply that (p+i) and (i+p) are different.  Nowhere
does it say "The pointer has to be first."  In fact, according to Harbison and
Steele's _C:_A_Reference_Manual_, 2nd edition, page 165:

	"For example, p+1 (or 1+p) points to the object after the
	one p points to, and p+(-1) (or (-1)+p) points to the 
	object just before."

Later, same page:

	"The + operator is assumed to be cummutative and associative,
	and the compiler is permitted to rearrange an expression with
	several additions, even in the presence of parentheses and
	without regard to overflow."

[Sorry for the extra information.  I wanted to quote in complete sentences.]

This time, not only is commutativity not ruled out, it is >expressly stated<,
without exceptions.

Admittedly, it's a bad idea to write "3[foo]" in place of "foo[3]", but there
is absolutely nothing in the language definition that prevents you from 
doing so without any loss of meaning whatsoever.  In my opinion, it's ugly
and unreadble, but it is most certainly legal.

So there.  Nyaah!

-- 
Jeff Erickson           Claris Corporation  | "MacWrite II is both sexy and
408/987-7309          Applelink: Erickson4  |   effective."
krazy@claris.com         ames!claris!krazy  |                -- MacWeek 4/18
         "I'm a heppy, heppy ket!"          |