Does `break` work only for `for`, `while`, `do-whi

2020-01-29 04:06发布

问题:

Suppose, I have a if statement inside a for loop:

for( ; ; )
{
  if( )
    {
     printf(" inside if");
     break;
    }//if         

  printf("inside for");
}//for

Now, will the break statement cause the compiler to come out of the for loop or will it only come out of the body of if once the condition in the if becomes satisfied?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

Break statement takes effect only on loops and switch clause. In any case it will come out from the nearest enclosing loop. It's a good practice to use a conditional break i.e. break enclosed by some if statement. If you want to come out of all the loops or some loop you can use goto statement. For example:

while(true) {
     while (some_condition) {
          if (some_condition)
               goto label;
     }
}
label: // do something here


回答5:

Break statement will not break any if or else statement. if you are using break statement it mainly come out from the nearest loop(for loop, while loop, do while loop and switch case)



回答6:

The break statement has no use in decison making statements. It is used only in loops, when you want to force termination from the loop and continue execution from the statement following the loop. There's no question of "will break statement cause the control to come out of the if statement if condition is true" , because irrespective of the break statement the control will anyway come out of the if statement if the condition is true and once its body is executed. The if statement is not a loop . it is either not exected at all or exectuted just once. So it absolutely makes no sense to put a break inside the body of if.



标签: c break