"abcdef"[3] == 3["abcdef"], but why?
Chris Torek
chris at mimsy.UUCP
Sat Sep 30 04:23:05 AEST 1989
In article <781 at cc.helsinki.fi> TEITTINEN at cc.helsinki.fi writes:
>Could someone explain to me what a C compiler does when it runs into
>expression 3["abcdef"]?
3["abcdef"] is of the form `e1 [ e2 ]' (e1 and e2 are arbitrary
expressions). Every C compiler converts this internally to
*( (e1) + (e2) )
(actually, compilers need only work *as if* they had done this
conversion, although many really do it). So we really have
*( 3 + "abcdef" )
To find out what this means, if anything, first try evaluating the
expression `3+"abcdef"'. This is
<value: int: 3> + <object: array 7 of char: `abcdef\0'>
Apply the rule for array objects in rvalue contexts: change `array N
of T' to `pointer to T', whose value is the address of the first (0th)
element of the array:
<value: int: 3> + <value: char *: points to `a' in `abcdef\0'>
We now have an expression of the form <int>+<pointer>, so we move to
the int'th element of the array that starts at *<pointer>. Here we
move to the 3rd element of `abcdef\0', which is the letter `c'. Now
we have
<value: char *: points to `c' in `abcdef\0'>
Now we can put the indirection back:
*( <value: char *: points to `c' in `abcdef\0'> )
The operand for `*' is a pointer, so we get the object to which the
pointer points:
<object: char: `c'>
Since e1[e2] is equivalent to *(e1+e2), if we reverse the expressions,
the only change is in the order of the operands to `+'. The result of
<pointer>+<int> is the same as that of <int>+<pointer>, so we wind up
with <object: char: `c'> again.
--
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