Does `break` work only for `for`, `while`, `do-while`, `switch' and for `if` statements?
The break
statement breaks out of the nearest enclosing loop or switch statement.
break
does not break out of an if
statement, but the nearest loop
or switch
that contains that if
statement. The reason for not breaking out of an if
statement is because it is commonly used to decide whether you want to break out of the loop
.
Interestingly, a telephone switch misbehaved because the company that invented C made exactly this bug. They wanted to break out of an if
statement and they forgot that it would break out of the entire for
statement.
It will break out of the for
loop. A break
statement only has an effect on loops (do
, for
, while
) and switch
statements (for breaking out of a case
).
From the C99 standard, section 6.8.6.3:
Constraints
A break statement shall appear only in or as a switch body or loop body.
Semantics
A break statement terminates execution of the smallest enclosing switch or iteration statement.
break
will not break out of an if clause, but the nearest loop or switch clause. Also, an if clause is not called a "loop" because it never repeats its contents.