Sukitha Udugamasooriya
Sukitha Udugamasooriya

Reputation: 2308

objective C for-loop break and continue

How can i use a 'break' statement within a for-loop which continues form a specified label?

ex;

outer: for(int i = 0;i<[arABFBmatches count];i++){
    for(int i = 0;i<[arABFBmatches count];i++){
        //
        break _____;
    }
}

How to break to outer?

Upvotes: 41

Views: 63365

Answers (5)

Suraj K Thomas
Suraj K Thomas

Reputation: 5883

'break' will only get you out of the innermost loop or switch. You can use 'return' to exit out of a function at any time.Please have a look at the this link.

Upvotes: 1

drphill
drphill

Reputation: 31

BOOL done = NO;
for(int i = 0;i<[arABFBmatches count] && !done; i++)
{
    for(int i = 0;i<[arABFBmatches count] && !done;i++)
    {
        if (termination condition) 
        {
             // cleanup
             done = YES;
        }
    }
}

Upvotes: 3

From Apple's Objective-C docs:

Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language.

So break and continue can be used wherever they are permitted in C.

continue can be used in looping constructs (for, while and do/while loops).

break can be used in those same looping constructs as well as in switch statements.

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Roughly:

for(int i = 0;i<[arABFBmatches count];i++){
    for(int j = 0;j<[arABFBmatches count];j++){
        //
        goto outer_done;
    }
}
outer_done:

Objective-C does not have labelled break.

Upvotes: 13

bbum
bbum

Reputation: 162712

Hard to say from your question. I'd interpret it that you want to skip the rest of the iterations of the inner loop and continue the outer loop?

for (int i = 0; i < [arABFBmatches count]; i++) {
    for (int j = 0; j < [arABFBmatches count]; j++) {
        if (should_skip_rest)
            break; // let outer loop continue iterating
    }
}

Note that I changed the name of your inner loop invariant; using i in both is inviting insanity.

If you want to break from both loops, I wouldn't use a goto. I'd do:

BOOL allDoneNow = NO;
for (int i = 0; i < [arABFBmatches count]; i++) {
    for (int j = 0; j < [arABFBmatches count]; j++) {
        if (should_skip_rest) {
            allDoneNow = YES;
            break;
        }
    }
    if (allDoneNow) break;
}

Upvotes: 110

Related Questions