writing C / C++ Program without a main() function | CTechnotips

This is logical trick.  who are unaware of it, can learn this trick.

#include<stdio.h>
#include<conio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)
void begin()
{
    clrscr();
    printf("\n Hello World !!! ");
    getch();
}

Explanation :


Here I am using pre-processor directive #define with arguments to give an impression that the program runs without main(). But in reality it runs with a hidden main().

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

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

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 I pass (s,t,u,m,p,e,d) as argument it merges the 4th,1st,3rd & the 2nd characters.

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

Here the pre-processor 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 “void begin” is replaced by “void main” by the pre-processor before the program is passed on for the compiler.

0 comments:

Post a Comment