prev up next   top/contents search

comp.lang.c FAQ list · Question 6.11

Q: I came across some ``joke'' code containing the ``expression'' 5["abcdef"] . How can this be legal C?

A: Yes, Virginia, array subscripting is commutative in C. [footnote] This curious fact follows from the pointer definition of array subscripting, namely that a[e] is identical to *((a)+(e)), for any two expressions a and e, as long as one of them is a pointer expression and one is integral. The ``proof'' looks like

	*((a) + (e))	(by definition)
	*((e) + (a))	(by commutativity of addition)
	e[a]		(by definition)

This unsuspected commutativity is often mentioned in C texts as if it were something to be proud of, but it finds no useful application outside of the Obfuscated C Contest (see question 20.36).

Since strings in C are arrays of char, the expression "abcdef"[5] is perfectly legal, and evaluates to the character 'f'. You can think of it as a shorthand for

	char *tmpptr = "abcdef";

	... tmpptr[5] ...
See question 20.10 for a realistic example.

References: Rationale Sec.
H&S Sec. 5.4.1 p. 124, Sec. 7.4.1 pp. 186-7

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North