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.
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