Loops and Jump Statements

Article · 1:00

for, while and do-while; break, continue, and the one legitimate use of goto.

The three loops differ in where the test happens. while tests before each iteration, so the body may never run. do ... while tests after, so the body always runs at least once - which is right for a menu that must be shown before the user can choose to leave. for is a while with the initialiser, test and increment collected on one line, which is why it suits counting.

break leaves the innermost loop or switch. continue skips to the next iteration - and note that in a for loop the increment still runs, while in a while loop it does not, which is how continue in a hand-written while becomes an infinite loop.

The classic off-by-one is the loop condition. for (i = 0; i <= n; i++) over an array of n elements reads one past the end, because valid indices are 0 to n - 1. Use <, and prefer size_t for the counter so it cannot go negative.

goto deserves a fair hearing. It is genuinely bad for control flow in general, and it is the standard idiom for error cleanup in C, because the language has no destructors and no finally. A function that acquires three resources and must release whichever it got before failing is clearest as a ladder of labels at the end. That is how the Linux kernel does it, and it is more readable than the nested conditionals it replaces.

#include <stdio.h>
#include <stdlib.h>

int process(const char *path)
{
    FILE *in = NULL, *out = NULL;
    char *buffer = NULL;
    int result = -1;

    in = fopen(path, "rb");
    if (!in) goto done;                 /* nothing to release yet */

    out = fopen("out.bin", "wb");
    if (!out) goto close_in;            /* release in */

    buffer = malloc(4096);
    if (!buffer) goto close_out;        /* release out, then in */

    /* ... the actual work ... */
    result = 0;

    /* The ladder unwinds in reverse order of acquisition. C has no
       destructors and no finally; this is the idiom, not a code smell. */
    free(buffer);
close_out:
    fclose(out);
close_in:
    fclose(in);
done:
    return result;
}

int main(void)
{
    /* size_t, and < not <=: valid indices are 0 to n-1. */
    int values[] = {3, 7, 2, 9, 4};
    size_t n = sizeof values / sizeof values[0];

    for (size_t i = 0; i < n; i++) {
        if (values[i] == 2) continue;   /* the i++ still runs */
        if (values[i] == 9) break;      /* leaves the loop */
        printf("%d ", values[i]);
    }
    printf("\n");

    /* do-while: the body runs before the test, which is what a menu
       needs - show it once, then ask whether to show it again. */
    int choice;
    do {
        printf("1) go  2) quit : ");
        if (scanf("%d", &choice) != 1) break;
    } while (choice != 2);

    return 0;
}