C Program without a main function


The question which always dig my mind that is there any possible way to write a program which will execute without the existence of main function.
Well, as one of my faculty told me that everything is possible in programming.
So here is the code of a program without main function


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



Here, the first question which hits the mind that whether this program will execute or not ?
The answer is obviously YES. How to Compile a C Program 
Now you are also interested in the Logic behind this code, Great Keep Reading.

Here we are using pre processor directive #define with arguments to give an impression that the program runs without main.
The ‘##‘ operator is called the token pasting or token merging operator. That is we can merge two or more characters with it.
Take a look at 2nd line of code:

#define decode(s,t,u,m,p,e,d) m##s##u##t



What is the preprocessor doing here. The macro decode(s,t,u,m,p,e,d) is being expanded as “msut” (The ## operator merges m,s,u & t into msut). The logic is when you pass (s,t,u,m,p,e,d) as argument it merges the 4th,1st,3rd & the 2nd characters(tokens).

Switch to 3rd line now,

#define begin decode(a,n,i,m,a,t,e)



Here the preprocessor replaces the macro “begin” with the expansion decode(a,n,i,m,a,t,e). According to the macro definition in the previous line the argument must be expanded so that the 4th,1st,3rd & the 2nd characters must be merged. In the argument (a,n,i,m,a,t,e) 4th,1st,3rd & the 2nd characters are ‘m’,'a’,'i’ & ‘n’.

So the third line “int begin” is replaced by “int main” by the preprocessor before the program is passed on for the compiler. That’s it…

At the end we got the conclusion that there is no such program exist which will execute without the main function but by simple tricks we can bypass it.
Previous
Next Post »