Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call main() itself in c++?

Tags:

c++

#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?

like image 792
Mask Avatar asked Mar 28 '10 12:03

Mask


People also ask

Can the main call itself?

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.

What happens when main calls itself?

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.

Can I call main () in C++?

In practice, can you call main() ? Yes.

Can we call main function in other functions?

In C, we can call main() Function through other Functions. In C++, we cannot call main() Function through other functions.


1 Answers

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'
like image 91
Carl Walsh Avatar answered Sep 30 '22 01:09

Carl Walsh