-2
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a;

  while(1)
  {
    scanf("%d", &a);

    switch(a)
    {
        case 0;
            break;
    }
  }

  return 0;
}

If I have a loop and a switch inside it, I want to stop both of them. That's because a break just stops the switch. In the program, there is a loop that asks for a variable and then a switch case where if the variable is 0, the loop and the switch case must stop.

I tried to add a variable for the loop and change it in the case for stopping the loop, but it doesn't work.

Barmar
  • 741,623
  • 53
  • 500
  • 612
sashax
  • 11
  • 1
  • 2
    Can you please share the code that is causing the problem? – RQDQ Dec 16 '22 at 21:08
  • 1
    If you need a two-level break, in straight C pretty much your only choice is a `goto`, which might be the right solution or might indicate your code needs rearranging so you don't need the two-level break, after all. – Steve Summit Dec 16 '22 at 21:12
  • `do { } while (a != 0)` seems perfectly suited to this. – Max Dec 16 '22 at 21:15
  • 1
    Just change that switch to `if (a == 0) break;` – Kevin Dec 16 '22 at 21:17
  • One possibility is to change the `switch` to an `if` (`else if`, `else`) chain. This is particularly sensible if there are only a couple of cases in the `switch`. Otherwise, a `goto` is the primary way to deal with it. Another alternative is to use `bool break_loop = false; … while ((…existing condition…) && !break_loop) { switch (…) { case '0': break_loop = true; …; break; … } }`. – Jonathan Leffler Dec 16 '22 at 21:17
  • 2
    I'm not sure if it was appropriate to close this C question as a duplicate to a corresponding C++ question, because C++ is a different language. For example, some of the answers to the C++ question mention throwing an exception, which is specific to C++, but not C. – Andreas Wenzel Dec 16 '22 at 21:28
  • Depending on whether or not `a` needs to be processed (like other values) before exiting the `while()`, simply add an `if( a == 0)` conditional to `break;` before-or-after the `switch()` block, but within the `while()` block. – Fe2O3 Dec 16 '22 at 23:26

1 Answers1

3

There are multiple ways to do this. Three follow.

Use a goto:

while (1)
{
    scanf("%d", &a);

    switch (a)
    {
        case 0:
            goto AfterWhile;
    }
}
AfterWhile:

Build code into the loop:

_Bool KeepGoing = 1;
while (KeepGoing)
{
    scanf("%d", &a);

    switch (a)
    {
        case 0:
            KeepGoing = 0;
            break;
    }
}

Encapsulate in a function and use return:

void DoTheLoop(void)
{
    while (1)
    {
        int a;
        scanf("%d", &a);

        switch (a)
        {
            case 0:
                return;
        }
    }
}
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312