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 anif
statement. Butbreak
s don't break out ofif
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");
break
out ofif
statement until theif
is inside a loop.break
statement is well specified and, generally, well understood. An inexperienced coder may cause crashes though a lack of understanding in many ways. Misuse of thebreak
statement isn't special.if
, it breaks out of thewhile
loop. C does not allowbreak
when not inside awhile
,for
, orswitch
.