Labels and goto

Learn the use of labels and the “goto” keyword.

Labels

Labels are names given to lines of code in order to direct program flow to those lines later on.

A label consists of a name and the : character:

end:   // ← a label

This label gives the name end to the line that it is defined on.

Note: In reality, a label can appear between statements on the same line to name the exact spot that it appears, but this is not a common practice:

anExpression(); end: anotherExpression();

goto

goto directs program flow to the specified label:

Press + to interact
import std.stdio;
void foo(bool condition) {
writeln("first");
if (condition) {
goto end;
}
writeln("second");
end:
writeln("third");
}
void main ()
{
foo(true);
}

When the condition is true, the program flow goes to label end, effectively skipping the line that prints “second.”

goto works the same way as in the C and C++ programming languages. Being notorious for making it hard to understand the intent and flow of code, goto ...