简体   繁体   中英

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?

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();
     }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM