"abcdef"[3] == 3["abcdef"], but why?
William B. Tyler
tyler at procase.UUCP
Tue Oct 3 04:05:00 AEST 1989
In article <781 at cc.helsinki.fi> TEITTINEN at cc.helsinki.fi writes:
>
>As I was trying to figure out what the cryptic maze program (posted to
>net some days ago) does, I ran into a very interesting feature of C. The
>program exploiting the fact that the following equation is true
>
> "abcdef"[3] == 3["abcdef"] (both equal to 'd')
>
>In fact, not only the values are the same. If the string "abcdef" was
>replaced by a pointer to char, the expressions would refer to the same
>memory location! This can't be a compiler-dependent feature (or bug)
>because the maze program runs correctly on various machines.
>
>Could someone explain to me what a C compiler does when it runs into
>expression 3["abcdef"]?
This is a standard, though little-known part of the C language.
The expression a[b] is defined to mean the same thing as
*(a+b). The result you obtained follows naturally from the rules
for pointer arithmetic.
Bill Tyler
--
Bill Tyler ...(tolerant|hpda)!procase!tyler
More information about the Comp.lang.c
mailing list