August 04, 2007

IOCCC Korn 1987

The IOCCC (International Obfuscated C Code Contest) is a yearly competition to write clever or underhanded C code. David Korn's 1987 one-liner is one of my favorite IOCCC entries for its density.

main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}

When run, this one-liner prints the string "unix".

Understanding this one-liner hinges on understanding that a[i] = i[a] in C; this is because both are *(a + i) and addition is commutative.

The mysterious "unix" appearing twice here is a traditional macro, defined on UNIX systems; In modern code, it has been surpassed by __unix__. It is directing the printf to start at the first (not zeroth) character of the string. The \021 and \012 are octal - the \021 is placed in here for trickery and deceit, which the \012 is the same is \n.

Lets simplify, so that printf is just printing a string and a newline:

main() { printf("%six \n",(unix)["have"]+"fun"-0x60);}

Now, the second part is trickier - we have (unix)["have"], which is the first (not zeroth) character of the string "have", which is 'a'. We are then adding this character to the string "fun" and subtracting 0x60.

The trick is that the character 'a' is 0x61; subtracting 0x60 leaves us with the string 1 + "fun". And now the magic - in C, the string literal functions as a pointer. "fun" + 1 is "un".

This whole line is the same as:

main() { printf("%six \n", "un");}

It should now be clear why this program prints "unix".

main

Posted by vsrinivas at August 4, 2007 07:00 AM