0

I'm trying to break from a while loop in a switch statement but it's not working. I get an infinite loop. Why?

int main()
{
    int n;
    while (std::cin >> n)
    {
         switch (n)
         {
         case 4:
             break;
             break;
         default:
             std::cout << "Incorrect";
             break;
         }
    }
}
template boy
  • 10,230
  • 8
  • 61
  • 97

2 Answers2

4

You get an infinite loop because that's not how break works. Once the first break executes, you exit the switch statement and the second break never executes. You'll have to find another way to exit the outer control structure. For example, set a flag in the switch statement, and then check that flag at the end, or in the loop condition.

while (std::cin >> n)
{
    bool should_continue = true;
    switch (n)
    {
    case 4:
        should_continue = false;
        break;
    default:
        std::cout << "Incorrect";
        break;
    }
    if (!should_continue)
        break;
}
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
1

break within a switch breaks the switch. Do somthing like:

while (std::cin >> n)
{
     if(n == 4)
         break;
     switch (n)
     {
     //...Other case labels
    default:
         std::cout << "Incorrect";
         break;
     }
}
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281