Obfuscated Main
I have been running a mailing list called ncoders on Yahoo
Groups for the past few months. I created it to host discussions on
computers, programming, and network protocols among university
students. There are currently about 150 students from various
universities across the world on the list. A few weeks ago, someone
posted a C programming puzzle to the group. The puzzle asked
whether it was possible to write a C program such that the
main()
function does not seem to appear in the
code. Here's a solution I came up with, which involves obfuscating
the identifier main
using preprocessor macros and
the ##
token-pasting operator.
#include <stdio.h>
#define decode(s,t,u,m,p,e,d) m ## s ## u ## t
#define begin decode(a,n,i,m,a,t,e)
int begin()
{
printf("Stumped?\n");
}
This program compiles and runs successfully. Here is the output:
Stumped?
Let me explain how this code works. When the C preprocessor runs on this code, the following preprocessing steps occur:
-
begin
is replaced withdecode(a,n,i,m,a,t,e)
, -
decode(a,n,i,m,a,t,e)
is replaced withm ## a ## i ## n
, and -
m ## a ## i ## n
is replaced withmain
.
Thus begin()
is replaced with main()
.
Update on 31 Jul 2007: Although the mailing list referred to in this post no longer exists, this tiny piece of code seems to have survived on the web. A quick search shows so many occurrences of this code on the web. It is quite surprising to me that a rather silly piece of code written during a Sunday afternoon to solve an equally silly puzzle has been the subject of much discussion!