Two 'main' functions in C/C++

后端 未结 16 1460
一整个雨季
一整个雨季 2020-12-01 16:08

Can I write a program in C or in C++ with two main functions?

16条回答
  •  心在旅途
    2020-12-01 16:34

    Standard C doesn’t allow nested functions but GCC allows them.

    void main()
    
    {
    
    void main()
    
    {
    
    printf(“stackoverflow”);
    
    }
    
    printf(“hii”);
    
    }
    

    The o/p for this code will be -hii

    if you use GCC compiler.

    There is a simple trick if you want to use 2 main() in your program such that both are successfully executed;you can use define.Example-

    void main()
    
    {
    
    printf("In 1st main\n");
    
    func1();
    
    }
    
    #define main func1
    
    void main()
    
    {
    
    printf("In 2nd main\n");
    
    }
    

    Here the o/p will be:

    In 1st main

    In 2nd main

    NOTE:here warning conflicting types of func1 will be generated.

    And yes don’t change the place of define.

提交回复
热议问题