On Thu, Dec 2, 2010 at 6:03 PM, Eric Smith <eric at brouhaha.com> wrote:
C permits a lot of interesting things. ?I've
occasionally interviewed
programmers claiming to be C experts, and amongst my questions for them are
whether the following is valid C code, what will happen when it is executed,
and why:
#include <stdio.h>
int main ()
{
?int i;
?for (i = 0; i < 14; i++)
? ?putchar (i ["Hello, world!\n"]);
}
So far none of the self-styled C experts I've interviewed were able to
answer all three questions correctly.
Hmm...
Looking at what's there, I'd say that it wouldn't surprise me that
some compilers would accept it (gcc does) and some might not, but what
it's going to do is to loop 14 times, then, using i as a pointer to an
array (for which the pointer values will range from 0-13), the loop
will sequentially access the Nth element of that array, but since "N"
happens to be the fixed address of the string "Hello, World!\n", the
effective calculation will be to sequentially point to each character
in the string (0+start address, 1+start address...) and feed the
"char" at that address to putchar() which will print it to stdout.
So... it will iterate across the static string one char at a time, but
by doing the pointer math "backwards" from the traditional technique
(i.e., a fixed index to a moving array pointer). The end result is
"Hello, World\n" sent to stdout.
Note that I do not claim to be a C expert; I am just
skeptical of most
people who claim to be such. ?I don't expect a C expert to necessarily know
the answer offhand, but they should be able to figure it out. If they can't,
they clearly don't know C anywhere near well enough to be considered expert,
as this problem is based on fundamental principles of the language.
I do represent myself in the workplace as a C expert, so hopefully I
passed the audition.
-ethan