Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break inside switch Cannot Terminate FOR Loop [duplicate]

I have a code snippet :

int n = 0;
for (int i = 0; i < 50;i++)
{
    n = checkStatus();
    switch (n)
    {
       case 1:
          break;
          break;//This is unreachable and so i cannot Terminate the For Loop within the SWITCH
    }
}

As described in a comment I cannot terminate the For Loop directly from the Switch, only if I declare a boolean and at the End of Switch test

if(LoopShouldTerminate)
    break;

PS : or maybe I'm very confused!

[POST] I got the message ,and the problem is Solved ,but i would like to asume that using Switch within a for loop isn't a god idea ,because i heard from lot of developer's i should break from loop in the moment when i get the desired result ,so using switch need's extra boolean or push the Int i value to 50 direclty , but what would happen if we're using while loop ?

like image 934
Rosmarine Popcorn Avatar asked Sep 08 '11 17:09

Rosmarine Popcorn


People also ask

Does Break break out of a switch statement?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

Can we write switch case inside for loop?

It is not necessarily an antipattern to use a switch statement within a loop—it is only considered incorrect when used to model a known sequence of steps. The most common example of the correct use of a switch within a loop is an inversion of control such as an event handler.

Does switch need break if return?

No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.


1 Answers

Solution 1: Move the loop and the switch to different methods:

for(int i = 0; i < 50; ++i)
{
    if (DoCheckStatus(i)) break;
}

...

bool DoCheckStatus(int i)
{
    switch(CheckStatus(i))
    {
        case 1 : return true;
        default: return false;
    }
}

Solution 2: Adapt the above to eliminate the loop with an eager extension method:

static void DoWhile<T>(this IEnumerable<T> sequence, Func<T, bool> predicate)
{
    foreach(T item in sequence) 
        if (!predicate(item)) return;
}

...

Enumerable.Range(0, 50).DoWhile(DoCheckStatus)

Solution 3: Adapt the above to eliminate the loop and the helper method:

Enumerable.Range(0, 50).DoWhile(i=> 
{ 
    switch(CheckStatus(i))
    {
        case 1 : return true;
        default: return false;
    }
});
like image 195
Eric Lippert Avatar answered Sep 29 '22 23:09

Eric Lippert