Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c - Does `break` work only for `for`, `while`, `do-while`, `switch' and for `if` statements?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...