No. In the 1st snippet, the break statement will exit from whatever loop or case statement the code snippet is embedded in. In the 2nd snippet, the break statement exits from the for loop itself only. I hope this helps.
Edit: I should add that in first snippet, most of (entire?) the array is examined, where as in the 2nd snippet, the for loop is exited from earlier.
Last edited by rjgibert on Thu Aug 12, 2010 3:22 am, edited 2 times in total.
rjgibert wrote:No. In the 1st snippet, the break statement will exit from whatever loop or case statement the code snippet is embedded in. In the 2nd snippet, the break statement exits from the for loop itself only. I hope this helps.
rjgibert wrote:No. In the 1st snippet, the break statement will exit from whatever loop or case statement the code snippet is embedded in. In the 2nd snippet, the break statement exits from the for loop itself only. I hope this helps.
But ............ let's revisit this.
If cnt is 20, and at cnt=8, the condition is true and B = TRUE, then why iterate through 9-20? It seems on the first instance the condition is true, the break exits without a need to see if the if-condition is true from cnt=9 to cnt=20.
benstoker wrote:
If cnt is 20, and at cnt=8, the condition is true and B = TRUE, then why iterate through 9-20? It seems on the first instance the condition is true, the break exits without a need to see if the if-condition is true from cnt=9 to cnt=20.
No, in the first snippet of code, the loop will go through all 20 iterations, and then it will break out of whatever loop or switch statement the snippet is in.
In the second snippet the `break' applies to the loop on `i'.
If you don't want to add an extra test to the condition of the inner loop, another way to break out of both loops at the same time is to use goto. Using goto as a multi-level break statement like this is a completely safe and reasonable use of goto.
/* some outer loop.. */
while (whatever)
{
for ( i = 0; i < cnt; i++ )
{
if ( HashStack[i] == Position->StateInfo->HASH )
goto Label1;
}
}
Label1:;
I usually prefer to write this rather than adding extra conditions to my loops; it seems clearer to say exactly what I mean even if the compiler is capable of rearranging them both into the same thing during its optimization passes.
B = FALSE;
for (i = 0; i < cnt; i++) {
if (HashStack[i] == Position->StateInfo->HASH)
B = TRUE;
}
if (B)
break;
Like Wylie Garvin, I also recommend using `goto' to break out of nested loops. Alternatively, if the loop can be given a clear name and a clean interface, I might move it to its own function, and then you just need to use `return'. As a general rule, do whatever makes the code most clear.