Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

break

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?

like image 899
avi Avatar asked Apr 02 '10 08:04

avi


People also ask

Do breaks work in if statements?

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 .

Does Break work for switch statement?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

Is break only for while loop?

The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .

Does break only exit if statement?

A break breaks from a loop and not from if statement. Show activity on this post. break is only for loops and switch statements. It ignores the if s and it will leave the loop, as required.


1 Answers

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.

like image 172
Windows programmer Avatar answered Oct 10 '22 06:10

Windows programmer