How to write a running C code without main()?

Write a C language code that prints GeeksforGeeks without any main function.

Logically it’s seems impossible to write a C program without using a main() function. Since every program must have a main() function because:-

  • It’s an entry point of every C/C++ program.
  • All Predefined and User-defined Functions are called directly or indirectly through the main.

Therefore we will use 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. Let’s see how the preprocessor doing their job:-

up

Hence it can be solved in following ways:-

  1. Using a macro that defines main
    #include<stdio.h>
    #define fun main
    int fun(void)
    {
        printf("Geeksforgeeks");
        return 0;
    }
    Output: Geeksforgeeks
  2. Using Token-Pasting Operator
    The above solution has word ‘main’ in it. If we are not allowed to even write main, we can use token-pasting operator (see this for details)

    #include<stdio.h>
    #define fun m##a##i##n
    int fun()
    {
        printf("Geeksforgeeks");
        return 0;
    }
    Output: Geeksforgeeks
  3. Using Argumented Macro

    #include<stdio.h>
    #define begin(m,a,i,n) m##a##i##n
    #define start begin(m,a,i,n)
    
    void start() {
       printf("Geeksforgeeks");
    }
    
    Output: Geeksforgeeks
  4. Refer Executing main() in C – behind the scene for another solution.

    References:
    Macros and Preprocessors in C

    This article is contributed by Abhay Rathi and improved by Shubham Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.