#include <iostream>
#include <cstdlib>
int main() {
cout << "!!!Hello World!!!" << endl;
system("pause");
return main();
}
The above works, but it hardcoded the main()
function. Is there a magic variable or macro to get the current running function?
The main() function can call itself in C++. This is an example of recursion as that means a function calling itself. A program that demonstrates this is given as follows.
The process of calling a function by the function itself is known as Recursion. Well,you can call a main() within the main() function ,but you should have a condition that does not call the main() function to terminate the program. Otherwise,the program will never return and run infinitely.
In practice, can you call main() ? Yes.
In C, we can call main() Function through other Functions. In C++, we cannot call main() Function through other functions.
Is it allowed in "C++"? No.
In practice, can you call main()
? Yes.
Whatever the C++ Standard says, that doesn't stop the Linux g++ compiler from compiling code with main()
in main()
.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int y = rand() % 10; // returns 3, then 6, then 7
cout << "y = " << y << endl;
return (y == 7) ? 0 : main();
}
Which lets us do:
> g++ g.cpp; ./a.out
y = 3
y = 6
y = 7
Looking in to the assembly, we see that main is called just like any other function would be:
main:
...
cmpl $7, -12(%rbp)
je .L7
call main
...
.L7:
...
leave
ret
Not that this behavior is guaranteed, but it looks like g++ doesn't seem to really care about the standard, apart from this sarcastic warning with -pedantic
g.cpp:8: error: ISO C++ forbids taking address of function '::main'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With