Saturday 6 August 2011

Writing a C program without a main()


We all are aware of what C programming language is. We often write huge programs which has numerous lines of code, but have you ever thought of writing a C program without a "main()" header??
You probably must be thinking this guy is nuts. But I haven't gone nuts yet studying my C & 
C++ books prescribed in my engineering college syllabus. And its possible to write a code in C programming language without using a main header.




 
let me show you how this can be done. 



#include<stdio.h>
#define decode(c,o,m,p,u,t,e,r)p##e##u##t
#define begin decode (t,e,r,m,i,n,a,l)
int begin()
{
printf("Demo of code without main");
}
 

Try running this program, and you will find it runs perfectly fine even without a main header.



Well now lemme tell you the truth, its not that I haven't used "main", its just that I have coded it in something else. A very small trick is involved here. Here the trick is done with the help of "#define" in the line 2 and 3.

In line 2:
#define decode(c,o,m,p,u,t,e,r)p##e##u##t


Here "##" operator is "Token merging operator" or pasting operator which merge two or more character together. Now in the line 2 (c,o,m,p,u,t,e,r) is expanded to “peut” as ## operator merges “p##e##u##t” to “peut”. The logic is when you pass (c,o,m,p,u,t,e,r) as argument it merges the 4th,7th,5th, and the 6th characters.


Now check the line 3:
#define begin decode(t,e,r,m,i,n,a,l)


Here again the preprocessor replaces the macro start with the expansion decode(t,e,r,m,i,n,a,l). As the macro definition in the line 2 the argument must be expanded so that the 4th,7th,5th, 6th characters must be merged. In the argument (t,e,r,m,i,n,a,l) 4,7,5, 6 nd characters are ‘m’,’a’,’i’, ‘n’.


So the fourth line “int begin” is replaced by “int main” by the preprocessor before the program is passed on for the compiler. Hence our program runs successfully.





This is a small trick which makes people believe that a program or piece of code can run without main.