Another silly question

Lloyd Kremer kremer at cs.odu.edu
Wed May 3 02:37:04 AEST 1989


In article <17812 at cup.portal.com> Tim_CDC_Roberts at cup.portal.com writes:

>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?
>.........
>Is a compiler force to examine all of the
>elements in a pointer expression and establish the "master type" of the
>expression?  If I mix two pointer types, as in
>  char * c;
>  long * ell;
>     return c + ell;
>is this anarchy?  Is it a syntax error?  What is sizeof(*(c+ell))?


Anarchy?  Yes, pointer addition has never been defined in C.
Syntax error?  I guess so.  Lint says, "operands of + have incompatible types."
Sizeof?  The expression is not defined, so its size certainly is not.

As to the conceptual implementation of a[i], the compiler sees a pointer a, and
an int i.  As has been shown, it does not matter which is in the brackets and
which is outside.  It does matter which is the pointer and which is the
integer, but since C is a type-oriented language, it does know this.

Many compilers immediately translate a[i] into *(a + i).  (Yet another
demonstration of their equivalence!)  a+i is an address which is evaluated as:
{machine address referenced by "a"} plus {"i" times sizeof(*a)}.
a[i] or *(a + i) is then the object of type *a located at that address.

Although 2["hello"] is cryptic, a compiler *should* get it right according to
the language definition (old or new).  If I observed a certain compiler to fail
on it, my confidence in that compiler to perform properly in other areas would
decrease by several orders of magnitude.

Another of these "confidence-diminishing" tests is 'sizeof("string")'.
The correct answer is 7.  Compilers that say 'sizeof(char *)' are broken.

-- 
					Lloyd Kremer
					Brooks Financial Systems
					...!uunet!xanth!brooks!lloyd
					Have terminal...will hack!



More information about the Comp.lang.c mailing list