Search code examples
cstandards

C: Can there be two main() functions in a program?


I saw other questions about having two main()'s in C program:

I'm using CodeBlocks

But please consider this program:

void main()
{
    void main()
    {
        printf("hello!");
    }
    printf("World!");

}

prints only "World!".

  • I'm actually writing these kind of code pieces to check what's happening under the hood.
  • I somehow get the doubts( as i get errors and unexpected behaviours in my programs ) by writing weird codes but I'm unable to know why they happened
  • Is there any reference to C language that i can refer to? Thanks in Advance.

Solution

  • Standard C and C++ do not support nested functions, but:

    1. GCC supports nested functions in C, as a language extension.
    2. The D language, which is C-related, has nested functions.

    and CodeBlocks use GCC compiler only, hence you're are not getting any error.

    For the question

    about having two main() in C program

    No you can't, this is how compiler interprets where to start executing the program. It will take one of the main as local.

    Also,

    you are not getting "hello" printed

    because when compiler starts executing your first main() function, it takes the second main() as local, and because you haven't called the second main(), the string doesn't get printed.