sujeet
sujeet

Reputation:

Why can't we have two main functions in C language?

Can someone explain me what happen internally happens, except that main is the start point and we cannot have two start point.

int main()
{
   int main()
   {
      return 0;
   }
   return 0;
}

Upvotes: 1

Views: 225

Answers (3)

templatetypedef
templatetypedef

Reputation: 373492

This isn't legal C code - in C, functions can't be defined inside of one another.

There's no fundamental reason that you couldn't do this, but implementing functions like this either complicates the activation record layout and would hurt efficiency (because of considerations like closures) or introduces the potential for memory errors (if you return a pointer to a function inside another function, and the inner function refers to data in the outer function, what happens?) In the interests of simplicity and efficiency, C just doesn't support this.

Hope this helps!

Upvotes: 3

Narraxus
Narraxus

Reputation: 41

Because the program must have a starting point. Function that is named as 'main' is the default starting point in C. That's why 'main' as a name is reserved by the C, and you cannot have another function named 'main'.

Upvotes: 0

Standard C doesn't allow defining a function inside another function. Some compilers support this as an extension, but the names have to be different, otherwise calling a function by its name would be ambiguous.

main is the program's entry point. A program has a single entry point, by definition: it's the function that is executed when the program starts (after some initialization), and the program exits when this function returns (after some cleanup).

Upvotes: 2

Related Questions