Decode Stumped

By Susam Pal on 02 Nov 2003

A few weeks ago, someone posted a C programming puzzle to the ncoders mailing list. This is a mailing list I formed a few months ago to host discussions on computers, programming, and network protocols among university students. The programming puzzle that was posted asked if we could write a C program such that the main() function does not seem to appear in the code. Here is a solution I could come up with that involves obfuscating the identifer main using preprocessor macros and the ## preprocessing operator for token concatenation.

#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:

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!

Comments