Search code examples
cloopsbreak

Does the break statement break out of multiple loops?


If I have a while loop (a) inside another while loop (b) and I use the break statement while in the 'b' loop, does it also break out of the 'a' loop or do I stay in the 'a' loop?


Solution

  • break; only breaks from the innermost loop or switch body it appears in.

    If you intend to break from nested loops, you might consider moving the nested loops to a separate function and using return to exit the function from any point inside its body.

    Example:

        ...
        int matrix[ROWS][COLS];
        int value;
        ...
        int found = 0;
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                if (matrix[row][col] == value) {
                    found = 1;
                    break;
                }
            }
            if (found)
                break;
        }
        ...
    

    Can be simplified as:

    int hasvalue(int matrix[ROWS][COLS], int value) {
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                if (matrix[row][col] == value)
                    return 1;
            }
        }
        return 0;
    }
    
        ...
        int matrix[ROWS][COLS];
        int value;
        ...
        found = hasvalue(matrix, value);
        ...