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;
}
}
}
}
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
break command (C and C++)The break command allows you to terminate and exit a loop (that is, do , for , and while ) or switch command from any point other than the logical end. You can place a break command only in the body of a looping command or in the body of a switch command.
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.
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.
If you put it inside for
loop it will stop/break the for
loop only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With