First excuse my newbie question. I am learning Objective C and very new to programming itself.
Can you guys explain me what causes a break or continue inside a loop?
For example, what is the difference between the two codes?
for (int i=0; i<100; i++) {
if ([self okToProceed]) {
[self doSomething];
} else {
break;
}
}
and
for (int i=0; i<100; i++) {
if ([self okToProceed]) {
[self doSomething];
} else {
continue;
}
}
Will the first code stop the loop the first time okToProceed returns false and the second loop simply continue to run, but doing nothing when okToProceed is false?
A break
statement exits the loop.
You can think of it as a means to create loop exit conditions.
For example, in your code: for(int i=0; i<100; i++)
, i<100
is a loop condition.
i.e. loop will exit if this condition is not met.
Similarly, inside if you have something like if(i == 34) { break; }
.
This will exit the loop when value of i
reaches 34 even though the loop exit condition specified was i<100
.
A continue
statement is used to skip to the next loop cycle.
This statement is used to basically avoid running the rest of the code within the loop.
Example:
for(i=0; i<5; i++) {
if(i == 3) {
continue;
}
print(i);
}
This loop will print 0 1 2 4
.
When i
will be 3, continue
will skip to the next loop iteration and the statements after continue
(i.e. print(i);
will not execute).
Ofcourse, the loop condition is checked before the loop runs.
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