Logo

Programming-Idioms

  • C++
  • PHP
  • Ada
  • Go

Idiom #42 Continue outer loop

Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.

Control flow jumping back to the beginning of the outermost loop
mainloop:
	for _, v := range a {
		for _, w := range b {
			if v == w {
				continue mainloop
			}
		}
		fmt.Println(v)
	}

mainloop is a label used to refer to the outer loop.
#include <iostream>
auto a = {1,2,3,4,5};
auto b = {3,5};

for (auto va: a){
    for (auto vb: b){
        if (va==vb) goto OUTER;
    }
    std::cout << va << '\n';
    OUTER: continue;
}
$array_1 = [1,2,3,4,5];
$array_2 = [3,4];

foreach ($array_1 as $a) {
    foreach ($array_2 as $b) {
        if ($b == $a) {
            continue 2;
        }
    }
    echo $a
}

The number next to the continue statement determines how many loops "up" it should skip. continue 1 is the same as continue with no numerical argument passed, and will skip to the next iteration of the current loop.
int *v = a;
while (v < a+N)
{
    int *w = b;
    while (w < b+M)
    {
        if (*v == *w)
            goto OUTER;
        
        ++w;
    }
    printf("%d\n", *v);
    
    OUTER: ++v;
}

N is the length of a.
M is the length of b.

Using goto is usually considered bad practice in C.

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