Hack 1 : Running a C program without main()

This  post is a simple example of deception. It shows how a programmer can defy the very important rule of having a main() in c program and still make the program run. This illustrates the concept on a simple program though it can be scaled to  much bigger and more complex programs.

#include<stdio.h>

#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)

int begin()

{
printf(” hello “);
}

This program runs without main().

how??

Here we are using preprocessor(a program which processes the source code before compilation.) 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.

In the 2nd line of the program-

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

Now look at the third line of the program –

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

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

So actually C program can never run without a main() . We are just disguising the main() with the preprocessor, but actually there exists a hidden main function in the program.

akshay pai

I am a data science engineer and I love working on machine learning problems. I have experience in computer vision, OCR and NLP. I love writing and sharing my knowledge with others. This is why I created Source Dexter. Here I write about Python, Machine Learning, and Raspberry Pi the most. I also write about technology in general, books and topics related to science. I am also a freelance writer with over 3 years of writing high-quality, SEO optimized content for the web. I have written for startups, websites, and universities all across the globe. Get in Touch! We can discuss more.

0 thoughts on “Hack 1 : Running a C program without main()

  • October 17, 2014 at 7:45 pm
    Permalink

    Hello! Someone in my Facebook group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and superb design and style. ggkegaagacea

    Reply

Leave a Reply

%d bloggers like this: