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

12,914

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
12,914
David Cosman
Author by

David Cosman

Updated on June 05, 2022

Comments

  • David Cosman
    David Cosman almost 2 years

    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;
                                }
                        }
                }
    }
    
  • John Dvorak
    John Dvorak over 11 years
    True in this case. Not true if the for loop is not the innermost loop.
  • Abubakkar
    Abubakkar over 11 years
    yeah I was particular with this case only.