How to make a C/C++ Program without main function



      We can't even think about a C or C++ program without main function in the program. But There is a  ways by which we can easily make a C/C++ program without main function. In reality behind the scenes, We're actually using a hidden main function. Every program must contain main function because:
  • It's the very first function called upon execution of program.
  • All other functions(either in-built or user defined) called through main function.
These all ways below uses the concept of Macro Substitution, so called preprocessor directives. Let's first understand the concept of preprocessor directives. Figure given below depict the whole process occurs while you compile your program.
      We don't wanna go in further details but at the very first step of compilation of any C/C++ program is passed through preprocessor. The preprocessor provides the ability for the inclusion of header files, macro substitutions etc. In simple words, it is a different program invoked by the compiler as the first part of the translation. It is responsible for removing all the comments from the program, include header files and functions, identifies, expand and substitute macros. 

      All these methods uses different approaches but ultimately they all fulfilling a sole purpose i.e. secretly hide or replace main function.

Method # 1 : Direct macro substitution




The above method simply substitutes the main function name with name function. We use #define which is a preprocessor directive. i.e. At the time of translation(a phase of compilation process), the preprocessor replaces all the occurrence of function with main. It simply replaces the argument given to right with the left.

Method # 2 : Token merging operator 


If someone asks you to make a program without using word main, then this way comes handy. The ## operator is used to merge two different tokens. So in this example, it also produces the same output without any error.

Method # 3 : Argumented substitution


As I told you before, we can substitute any keyword, token or even functions. The same concept we used here. In 2nd line of code, firstly I define a macro function called as decode and provide the method of it's working and In 3rd line I create a function named function and substitute it with the predefined function decode with different set of arguments. 

Comments

Popular Posts