David Cosman
David Cosman

Reputation: 433

C; If I put a break in a for loop inside a while loop

I am doing this in C, NOT C++. Anyways, if I put a break statement inside a for loop, will it stop the for loop only or both the for and the while loop? For example, here is the part of my code with the while and the for. What I'm doing is letting the user enter a 24 hour time, and I'm checking the minutes in this loop (which is hopefully correct). What I'm concerned about is if the break statement will end the for loop only or if it will end both the for and the while, since I only want the for loop to end.

boolean check = false;
while (!check){
    int i;
            for (i = 1; i < 24; i++)
            {
                    int hour = i*100;
                    /* if the time has less hours than the hour counter*/
                    if ((hour - timeOfDay) < 100)
                    {
                    /*declare an illegal time when the number of minutes remaining*/
                    /*is greater than 59*/
                            if ((hour - timeOfDay) > 59)
                            {  
                                    check = false;
                                    break;
                            }
                    }
            }
}

Upvotes: 5

Views: 14788

Answers (4)

Omkant
Omkant

Reputation: 9204

As break executes, the program stops executing the other statements below it and just come outside the loop and start from the statements just after the loop body where break is present. Here in this case it will just come out of the inner for loop. If you want to do some demo just put one statement (eg printf("outside inner loop");) after the closing curly brace } of for loop. Then you will see the execution of that statement.

Upvotes: 0

Jeyaram
Jeyaram

Reputation: 9474

From the C 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.

Upvotes: 5

Abubakkar
Abubakkar

Reputation: 15644

If you put it inside for loop it will stop/break the for loop only.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

It will only break the inner for loop and not the outer while loop.
You can actually test this with a minimalistic code sample before you posted the question.I guess it would take same amount of time as much as framing the Q.

Upvotes: 14

Related Questions