tags:

views:

89

answers:

3

Why does break statement ends the nested loop?it should get the iteration of the inner loop to stop while the outer loop should continue doing its work.

int main()
{
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
            break;
        }
    }

}

This code breaks at the first iteration.

+1  A: 

It does what you dont think it does.

break is used with the conditional switch statement and with the do, for, and 
while loop statements.

In a switch statement, break causes the program to execute the next statement 
after the switch. Without a break statement, every statement from the matched 
case label to the end of the switch, including the default, is executed.

In loops, break terminates execution of the nearest enclosing do, for, or 
while statement. Control passes to the statement that follows the terminated 
statement, if any.

Within nested statements, the break statement terminates only the do, for, 
switch, or while statement that immediately encloses it. You can use a 
return or goto statement to transfer control from within more deeply nested 
structures.

Some links from SO which will be helpful.

  1. Break from nested loops
  2. Controlling nested loops

The above text is from this link.

Praveen S
Where is this text from?
James McNellis
msdn? http://msdn.microsoft.com/en-us/library/37zc9d2w(VS.80).aspx
Imre L
@James McNellis,Imre L Yup! Edited it now.
Praveen S
How was the syntax highlighting removed? Let me know please :-(
Praveen S
+1  A: 

It does break only the inner loop. Add a bit more code to see what's really happening:

int main()
{
    for(int i=0;i<10;i++)
    {
        printf("Iteration %d of outer loop\n", i);
        for(int j=0;j<10;j++)
        {
            break;
        }
    }

}

Assuming your compiler works at least sort of close to correctly, the output should be:

Iteration 0 of outer loop
Iteration 1 of outer loop
Iteration 2 of outer loop
Iteration 3 of outer loop
Iteration 4 of outer loop
Iteration 5 of outer loop
Iteration 6 of outer loop
Iteration 7 of outer loop
Iteration 8 of outer loop
Iteration 9 of outer loop
Jerry Coffin
Thanks!Really helpful.
fahad
@fahad - Did you not run your program?
Praveen S
I runned the program long time ago and had this question in my mind.When i posted the question i was asked to put a code so i made a code myself.
fahad
A: 

The following:

#include <stdio.h>
int main()
{
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
            printf("i: %d j: %d\n", i, j);
            break;
        }
    }
}

produces this output:

i: 0 j: 0
i: 1 j: 0
i: 2 j: 0
i: 3 j: 0
i: 4 j: 0
i: 5 j: 0
i: 6 j: 0
i: 7 j: 0
i: 8 j: 0
i: 9 j: 0

which seems to be what you say you expect. Can you explain your question any better?

ysth