How to exit the FOR loop within the Switch structure?

Asked

Viewed 820 times

6

I’m in a noose FOR and I want to lock him inside the Switch, but when I give break within the Switch he comes out of Switch and continues the loop FOR, someone can tell me how to get out of the loop FOR?

Here’s the code:

bool variavel = true;

    for (int i = 0; i < length; i++)
    {
        switch (variavel)
        {
            case true:
            {
                break; // este break vai fechar o switch e não o laço
            }
            break; // este break não funciona e nunca é usado, por causa do break de cima            
            case false:
            {
            }
            continue; // continue funciona e retorna para o laço para que ele continue
        default:
            break; 
        }
    }

3 answers

9


These are two sketches that may or may not be applicable to your code, but I’ve come up with an alternative to what has already been posted. You have to scan the rest of the code to see which option fits, because it depends on how you use the loop variable, if you have any operation after the switch, these things you can only know with real code where the solution will be applied.

I posted two complementary possibilities - the first one performs anything that is inside the loop after the break one last time, and the second comes out of the loop straight from the case without doing anything else on for:


Finalizing loop :

The most usual way to get out of a for is not satisfying your condition (and this is what happens most of the time in a normal loop). We can use this to our advantage.

Here you set a condition for the loop carry on:

for (int i = 0; i < length; i++)

If the condition is i < length, any value equal to or greater than length for i brings out at the end of loop.

So just do i = length before the break desired:

bool variavel = true;

for (int i = 0; i < length; i++)
{
    switch (variavel)
    {
        case true:
        {
            i = length;
//          ^^^^^^^^^^^^ Pronto, a condição para continuar o loop foi desfeita
            break; // este break vai fechar o switch e não o laço
                   // mas o laço em si vai terminar por causa da linha anterior
        }
        case false:
        {
        }
        continue; // continue funciona e retorna para o laço para que ele continue
    default:
        break; 
    }
    // Esta parte aqui ainda sera executada uma ultima vez
    // apos o case true
}


Using goto:

One way out that might be interesting in these cases is the goto.

Take the example of the microsoft documentation (added some comments):

public class GotoTest1
{
    static void Main()
    {
        int x = 200, y = 4;
        int count = 0;
        string[,] array = new string[x, y];

        // Initialize the array:
        for (int i = 0; i < x; i++)

            for (int j = 0; j < y; j++)
                array[i, j] = (++count).ToString();

        // Read input:
        Console.Write("Enter the number to search for: ");

        // Input a string:
        string myNumber = Console.ReadLine();

        // Search:
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                if (array[i, j].Equals(myNumber))
                {
                    goto Found; // AQUI VOCÊ ESCOLHE O DESTINO
                }
            }
        }

        Console.WriteLine("The number {0} was not found.", myNumber);
        goto Finish;

    Found: // ESTE É UM LABEL, VOCÊ  DEFINE O NOME DESEJADO
        Console.WriteLine("The number {0} is found.", myNumber);

    Finish: // ESTE É UM LABEL, VOCÊ  DEFINE O NOME DESEJADO
        Console.WriteLine("End of search.");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

I took the original example to avoid typos. In your case it will be simpler yet:

bool variavel = true;

for (int i = 0; i < length; i++)
{
    switch (variavel)
    {
        case true:
        {
            // Se vai sair do loop, não precisa fechar o switch
            // faz o que tem que fazer e...
            goto CaiFora;
        }
        case false:
        {
        }
        continue; // continue funciona e retorna para o laço para que ele continue
    default:
        break; 
    }
    // Esta parte aqui sera totalmente ignorada
    // apos o goto
}
CaiFora:
    // Aqui continua o código normalmente

Further reading:

Why the use of GOTO is considered bad?

  • 3

    I didn’t know about this resource, programming and learning!

8

You can try to put another condition on for

bool forceExit = false;
for (int i = 0; i < length && !forceExit; i++)
{
...
}

When you want to get out of it forceExit=true

  • 4

    It didn’t cross my mind

6

Extract the functionality of your grouped ties and make available in a function. This way you can use 'Return' to exit the loop from anywhere, instead of using 'break''.

Using your original example:

bool variavel = true;
for (int i = 0; i < length; i++) {
   switch (variavel){
      case true: break; //Entendo que este seja o ponto de quebra desejado, correto?
      default: break;
   }
}

I could use it this way:

bool verificaSeVerdadeiro(bool variavel){
   switch (variavel){
      case true: return true;
      default: return false;
   }
}
bool variavel = true;
for (int i = 0; i < length; i++) {
   if(verificaSeVerdadeiro(variavel)) break;
}


source: https://stackoverflow.com/questions/2339142/how-to-break-out-of-multiple-loops-at-once-in-c

Don’t Panic ^_^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.