Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Obj-c

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Control flow jumping forward after the end of the outermost loop
@import Foundation;
[m enumerateObjectsUsingBlock:^(NSArray *row, NSUInteger rn, BOOL *stopr) {
  [row enumerateObjectsUsingBlock:^(NSNumber *v, NSUInteger cn, BOOL *stopc) {
    if (v.intValue<0) {
      NSLog(@"found %@ at row:%lu col:%lu",v,rn,cn);
      *stopr=*stopc=YES;
      return; // to quit the current block immediately
    }
  }];
}];

Showing an imperfect work-around with blocks. If blocks are not used, goto is available: check the plain C idiom for an example. Note it might be tempting to use exceptions instead; do not: in ObjC it is considered a bad practice
Outer_loop:
for A in M'Range (1) loop
   Inner_Loop:
   for B in M'Range (2) loop
      if M (A, B) < 0 then
         Put_Line (M (A, B)'Image);
         exit Outer_Loop;
      end if;
   end loop Inner_Loop;
end loop Outer_Loop;

New implementation...
< >
programming-idioms.org