"A little progress everyday adds up to big results"

Monday 12 January 2015

A C program without main

               As soon as you see the title, you might be wondered whether this is possible. But, it's actually possible.  

#include<stdio.h>

#define modify(t, r, a, i, n, s) i ## t ## a ## r
#define change modify(a, n, i, m, a, l)

int change()
{
    printf("C without main!\n");
    return 0;
}


            If you still don't trust this program, compile and execute it. Shocked ? In fact, there is a main in this program, but hidden. This is based on the concept of token pasting. What happens here is, change is initially replaced by modify(a, n, i, m, a, l). The arguments are then replaced as follows
t = a
r = n
a = i
i = m
n = a
s = l

           The statement i ## t ## a ## r gets changed to m ## a ## i ## n, which is then concatenated as main. Eventually, 'change' is changed to 'main'.  Since all these steps take place even before compilation (at the macro expansion stage), the compiler does not throw an error.
Now, become a magician by showing this trick to your friends! 

No comments:

Post a Comment