C programme without main function…:)

 C PROGRAMME WITHOUT MAIN SURPRISED???

 

Ya thts true after a long issue about tht question I came to this conclusion. That we  can write a error free C programme without main function.

 

What is main  function in C:- Every C program has a primary (main) function that must be named main. The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. A program usually stops executing at the end of main, although it can terminate at other points in the program for a variety of reasons. At times, perhaps when a certain error is detected, you may want to force the termination of a program. To do so, use the exit function.

 

Writing a C programme without main:- Is it possible to do that. Yes there can be a C program without a main function. Here’s the code of the program without a main function…

#include<stdio.h>

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

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

int start()

{

printf(“’finally I got without main…..:)’”);

return 0;

}

HOW IT WORKS:- Does the above program run without the main function? Yes, the 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 the program runs without main. But in reality it runs with a hidden main function.

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

 

#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).

 

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

 

 

ü  Here the preprocessor replaces the macro “start” 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 start” is replaced by “int main” by the preprocessor before the program is passed on for the compiler. That’s it…

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

I HOPE ALL OF U ENJOYED THIS POST…:)

 

Advertisements