Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite Loops and Early Return Statements

I have a simple console application that outputs a menu and waits for user input. After performing the appropriate action, the entire process repeats. The program exits when a specific string is entered. This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement. He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
  • Is it really a bad idea to use an infinite loop and an early return statement?
  • If so, is there a technical reason or is it just bad practice?
like image 325
Maxpm Avatar asked Nov 27 '22 00:11

Maxpm


2 Answers

This might be one of those rare cases where do...while is appropriate. I avoid adding extra boolean state variables unless they genuinely make the code clearer.

int main()
{
    string UserChoice;
    do
    {
        OutputMenu();

        cin >> UserChoice;

        // ...

    } while (UserChoice != "exit");
}

However, for a user input loop I would usually make a function that returns whether or not the input was successful. As it stands the code could easily end in an infinite loop if cin closes.

E.g.

bool GetNonExitInput( std::istream& in, std::string& s )
{
    OutputMenu();
    in >> s;

    return in.good() && s != "exit";
}


int main()
{
    std::string UserChoice;

    while (GetNonExitInput(std::cin, UserChoice))
    {
        // ...
    }
}
like image 70
CB Bailey Avatar answered Dec 05 '22 05:12

CB Bailey


Really either is fine, but you need to do what your professor wants. You'll find it is the same in industry as well. Some companies may have a coding standard that dictates curly braces go on a new line, while others want them to start on the line that begins the block. There is no real reason to prefer one over the other, so it is best to just go with what the lead wants.

like image 45
ConsultUtah Avatar answered Dec 05 '22 04:12

ConsultUtah