Saturday, June 29, 2013

Program without a Main Function

We would be wondering that we can write a C program without a main function. Generally we know that a C program cannot be executed without a main function. But we can execute it without main. Just try out the code below, it works fine even without a main function in it.

#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(” hello “);
}


A bit confused why it is happening right... I will explain why this happens.

In the above example, we have used the directive #define for defining the function decode. The decode function takes 7 parameters and defined the function to be as m##s##u##t.

In C, ## is called as token merging operator, which means that the tokens before and after the ## are merged and seen as one. Thus for a function decode, it takes 4th, 1st, 3rd and 2nd parameters and mix them into one.

Thus decode(s,t,a,m,p,e,d) returns msut.
Similarly we have defined a function begin as decode(a,n,i,m,a,t,e).
decode(a,n,i,m,a,t,e) returns as main.
Hence begin takes the value as main.
Thus when we use the begin function, it takes it as main function and gets executed fine. It means that int begin() = int main().

Thus we can write a C program without a main function.