"break;" out of "if" statement?
c
Solution
`break` interacts solely with the closest enclosing loop or switch, whether it be a `for`, `while` or `do .. while` type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, `continue` and `break` interact with virtual labels automatically placed by the compiler. This is similar to what `return` does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding `break` as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that `G` would cause a jump to `I`, but it jumps to `J`. The intended function would use `if (!G) H;` instead.
Problem
Can you break out of an if statement or is it going to cause crashes? I'm starting to acquaint myself with C, but this seems controversial. The first image is from a book on C ("Head First C") and the snippet shows code written by Harvard's CS classes staff. What is actually going on and has it something to do with C standards? breaks don't break if statements. On January 15, 1990, AT&T's long-distance telephone system crashed, and 60,000 people lost their phone service. The cause? A developer working on the C code used in the exchanges tried to use a `break` to break out of an `if` statement. But `break`s don't break out of `if`s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours. ``` for (size = 0; size < HAY_MAX; size++) { // wait for hay until EOF printf("\nhaystack[%d] = ", size); int straw = GetInt(); if (straw == INT_MAX) break; // add hay to stack haystack[size] = straw; } printf("\n"); ```