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 ?
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.
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.
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.
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With