Another silly question
Chris Torek
chris at mimsy.UUCP
Wed May 3 09:19:10 AEST 1989
In article <17812 at cup.portal.com> Tim_CDC_Roberts at cup.portal.com writes:
>... 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 type of
"hello"
is
array 6 of char
(or
char [6]
if you prefer) which, in all contexts except declarations and targets
of sizeof(), changes to
pointer to char
with the value being the address of the first (zero'th) element of
the array. So the types of the two expressions
"hello"[2]
and
2["hello"]
are
(char *) [ (int) ]
and
(int) [ (char *) ]
The [] syntax means `add the value of the object to the left to
the value of the object to the right, then dereference':
* ( (char *) + (int) )
and
* ( (int) + (char *) )
respectively. Addition is defined on two cases: addition of scalar
types with other scalar types (such as int+int, or double+int, or
char+long) and addition involving pointers. Both additions involve
pointers, so both follow these rules, which are:
The result of <pointer to T> plus <integral expression whose
value is N> is the address of the N'th object of type T `away
from' the place where the pointer points, in the `increasing'
direction if N is positive, and the `decreasing' direction if
N is negative.
The result of <integral expression whose value is N> plus
<pointer to T> is the same as that of <pointer to T> plus
<integral expression whose value is N>.
No other additions involving pointers are legal.
>Doesn't that equivalence imply that the pointer type is somehow
>"stronger" than the simple type?
You might think of it as such; without a defintion of `strength' there
is no way to say.
>Is a compiler force to examine all of the elements in a pointer
>expression and establish the "master type" of the expression?
The compiler must look at both types in any dyadic operation (addition,
subtraction, multiplication, division, -> selection, . selection, etc.).
The result of the lookup can be found in a table in the language
definition.
>If I mix two pointer types ... is this anarchy? Is it a syntax error?
If the operation is addition, it is a semantic error: there is no
definition for the result of addition of two pointers. (The
subtraction operator allows two operands which are both pointers, but
they must have the same type.)
>(Please don't submit 30 replies saying "because the book says so"...)
s/book/language definition/, and you have the answer above (but without
all the verbiage).
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list