label

Summary

A label can be applied to a statement to give it a name; this name can later be referred to from 'break' and 'continue' statements.

Syntax

labelName: statement;

Parameters

labelName
The name for the label. This can be any valid identifier.
statement
The statement to apply the label to.

Description

A labelled statement is a statement that has been given a name. The name can later be referred to from the break and continue statements.

Labelled statements are especially useful when dealing with nested loops as they enable you to refer to a specific loop by its label.

break With Labels

1
2
3
4
5
outerLoop: for (int x = 1; x <= 5; ++x) {
    innerLoop: for (int y = 1; y <= 5; ++y) {
        break outerLoop;
    }
}

Notice we labelled the loops (outerLoop and innerLoop) at lines 1 and 2, respectively. We also provided a label (outerLoop) to the break statement at line 3. By referring to the outerLoop in our break statement, we were able to exit the outermost loop; without the label, we would not have been able to exit the outermost loop. (The innermost loop would have been exited since it is the closest loop to the break statement.)

continue With Labels

1
2
3
4
5
outerLoop: for (int x = 1; x <= 5; ++x) {
    innerLoop: for (int y = 1; y <= 5; ++y) {
        continue outerLoop;
    }
}

Notice we labelled the loops (outerLoop and innerLoop) at lines 1 and 2, respectively. We also provided a label (outerLoop) to the continue statement at line 3. By referring to the outerLoop in our continue statement, we were able to skip to the next iteration of the outermost loop; without the label, we would not have been able to skip to the next iteration of the outermost loop. (Instead, we would have skipped to the next iteration of the innermost loop since it is the closest loop to the continue statement.)

Labelling Blocks

Blocks can be labelled. We can also use the break keyword to break out of a labelled block:

1
2
3
4
5
myBlock: {
    int x = 1;
    break myBlock;
    int y = 2; // This statement will never be executed
}

See Also

Share

HTML | BBCode | Direct Link