tags:

views:

65

answers:

3

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 if loop on the 'if-condition' being satisfied.

+1  A: 

It will break out of the foor 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.
Mark Byers
Thank you Mr. Mark
+4  A: 

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.

Matti Virkkunen
Thank you Mr. Matti.
+2  A: 

The break statement breaks out of the nearest enclosing loop or switch statement. The reason why it doesn't just break out of an if statement and continue immediately inside the loop immediately after it is that a common idiom is to use an if statement to decide if 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.

Windows programmer
thank you Mr and that was a very informative example.I'm clear about it now.
[citation needed] :)
erelender
It was news around 20 years ago. erelender, you can Google it as well as I can, maybe starting with things like ess software bug break.
Windows programmer