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 o
I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if
inside. So, I'll try to answer this question with this particular interpretation.
If you have if
inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if
or was it ended "naturally"? So, your sample code can be modified in this way:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; break;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
The problem with this code is that the if
statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break
statement) variant will be:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; continue;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.
UPDATE:
Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break
to exit from both loops and switch
.
Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.