2
#include <iostream>

int main()
{
    main();
    std::cout<<"Hello World! "<<std::endl;
    return 0;
}

This is the code, How does it behave? Why?

Nagaraju
  • 1,853
  • 2
  • 27
  • 46
lkcumt
  • 43
  • 4
  • 2
    Have you tried running it? – Sambuca Aug 27 '13 at 08:47
  • If it was any other function than main you would get a stack overflow which would cause the program to crash. – Simon Aug 27 '13 at 08:53
  • @Sambuca: Running it in this case probably leads to a stack oveflow. However, "stack overflow" is not the real answer to this. – Sebastian Mach Aug 27 '13 at 08:54
  • +1 ... becuase I like this question :) and I did not know the specific rule that you could not recursively call a function named "main()" (not that one would want to!) But also, just a casual observation, even if this recursion worked as you expected it to you would not see any printed output because your call to main() is before your hello world print statement. – code_fodder Aug 27 '13 at 09:01
  • @MSalters: OK - duplicates specifically for C++: [Is it legal to recurse into main() in C++?](http://stackoverflow.com/questions/4518598/is-it-legal-to-recurse-into-main-in-c) and [Why are recursive main() calls not allowed in C++?](http://stackoverflow.com/questions/5326491/why-are-recursive-main-calls-not-allowed-in-c) – Paul R Aug 27 '13 at 09:03

5 Answers5

8

That's undefined behaviour. You cannot call main() from within a C++ program (section 3.6.1.3 of the standard).

Therefore anything can happen. And there's no point in asking why.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
3

main() function call itself in C++, what will happen?

Anything can happen, since it's undefined behavior. But as the program is currently standing, some infinite recursion (and eventually a stack overflow) seems reasonable.

3

You should not call main inside main, it is undefined behavior.

§ 5.2.2.9 Function call

Recursive calls are permitted, except to the function named main (3.6.1).

§ 3.6.1

The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is illformed. The name main is not otherwise reserved. [ Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. —end example ]

billz
  • 44,644
  • 9
  • 83
  • 100
1

In C++, calling main() from your is not allowed. So it is an error. Even taking its address is error.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

main() has only one entry point. So, its not allowed to be called again.

sr01853
  • 6,043
  • 1
  • 19
  • 39