Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent from calling main() recursively in C++

I have a similar code to the following:

int main()
{
    'some
     code'
     motors();
}

int motors()
{
     if (condition)
     {
          'some
           code'
           main();
     }
     else if (condition)
     {
          'some
           code'
           main();
     }
     else
     {
           main();
     }
}

What could I do to prevent from calling main over and over? Could I make another function with main's code in it?

like image 932
Sam Javed Avatar asked Jan 29 '26 11:01

Sam Javed


2 Answers

Calling main is undefined behavior in C++. You can wrap all the functions originally in main to another function.

int main()
{
    wrapper();
}

void wrapper()
{
    //code originally in main
}

And whenever you need to call main, call this wrapper instead.

int motors()
{
     if (condition)
     {
         wrapper();
     }
like image 183
Yu Hao Avatar answered Jan 31 '26 23:01

Yu Hao


There is a simple of avoiding calling a function recursively: Don't do it! In fact, there is seldom any need to call main from inside a program, and I think it's generally should be avoided at all cost (except for "clever hacks" such as those used in the IOCCC).

Instead, you should use loops:

int main()
{
    for (;;)
    {
        some_code_that_calls_motors();
    }
}

Then just return from the function, and the calling call-chain until you're back in main and the loop starts over.

like image 43
Some programmer dude Avatar answered Feb 01 '26 01:02

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!