Is calling main bad

closed account (EwCjE3v7)
Hi there
I was wondering is calling main() bad practice? from other functions and main
1
2
3
4
5
6
7
8
int main()
{
 main();
}
int test()
{
   main();
}


and is calling the same function from within itself bad to?
1
2
3
4
int test()
{
   test();
}


Last edited on
Calling main() is bad practice because the C++ standard says it's not allowed.

A function that calls itself is called a recursive function. Each function invocation (function call that has not yet returned) usually take up a piece of stack memory so you need to make sure the recursion is not too deep or otherwise you can run out of stack memory, getting a stack overflow. One way to get rid of this limitation is to implement the function using iteration (loops) instead.
Last edited on
closed account (EwCjE3v7)
Okay thank you Peter97, so I should avoid both?
Last edited on
No, depends on the problem you are trying to solve. A recursive function can always be implemented as an iterative function (using loops) and vice versa. You should prefer using iteration (loops) most of the time but recursion can be very useful and is sometimes the most straight forward way to implement something, especially at times when working with recursive data structures.
Last edited on
If your recursive function is properly tail recursive then all the major compilers (AFAIK) are smart enough to implement the tail-recursive call.
closed account (EwCjE3v7)
Thanks Peter and Duoas, I am going to just use a loop
Topic archived. No new replies allowed.