Menu

How To Write A C-Program Without Using main() Function?

Have you ever wondered whether you can write a program without main() function in C language to specify without a entry point..? The answer is NO. But with some tricks you can always think out of the box and do something you wish and write it without a main() function.

Here is an example to illustrate,

#include<stdio.h>

#include<conio.h>

#define Encyp(m,a,h,e,s,g,t) m##h##s##e

#define begin Encyp(m,e,a,n,i,n,g)

int begin()

{     clrscr();

printf(” hello “);

getch();

}

Program Snapshot

Explaination:

Does the above program run without main function? Yes,  above program runs perfectly fine even without a main function. But how, whats the logic behind it? How can we have a C program working without main?

Here we are using preprocessor directive #define with arguments to give an impression that  program runs without main. But in reality it runs with a hidden main function.

The ‘##‘ operator is called  token pasting or token merging operator. That is we can merge two or more characters with it.

NOTE: A Preprocessor is program which processes  source code before compilation.

Look at  second line of program –

#define Encyp(m,a,h,e,s,g,t) m##h##s##e

What is the preprocessor doing here. The macro Encyp(m,a,h,e,s,g,t) is being expanded as “mhse” ( ## operator merges m,h,s & e into mhse). Logic is when you pass (m,a,h,e,s,g,t) as argument it merges the 1st,3rd , 5th &  4th characters(tokens).

Now look at  third line of  program –

#define begin Encyp(m,e,a,n,i,n,g)

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

The number of arguments passed in  pre-defined statement Encyp and begin Encyp must be the same. Length of “m,a,h,e,s,g,t” is equal to  length “m,e,a,n,i,n,g”. If  length do not match compiler will throw an Error saying wrong number of arguments in call of macro ‘Encyp’ and declaration terminated incorrectly.So  third line “int begin” is replaced by “int main” by  preprocessor before the program is passed on for the compiler. That’s it…

Final Thoughts

The bottom line is there can never exist a C program without a main function. Here we are just playing a gimmick that makes us beleive  program runs without main function, but actually there exists a hidden main function in the program. Here we are using proprocessor directive to intelligently replace the word begin” by “main”. In simple words int begin=int main.