Search⌘ K
AI Features

Labels and goto

Explore how labels and the goto statement influence program flow in D programming. Understand why goto is discouraged and learn about safer alternatives like loop labels, structured control flow, and resource management techniques. This lesson clarifies correct and incorrect uses of goto for advanced D developers.

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:

D
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, ...