
Local Labels in C
There is no concept of “local labels” in the same way as some assembly languages or other programming languages may have. Labels in C are primarily used for defining points in code that can be targeted by control flow statements like goto.
Here’s a simple example of how labels and goto can be used in C:
#include <stdio.h>
int main() {
int i = 0;
loop_start: // Label
if (i < 5) {
printf("%d\n", i);
i++;
goto loop_start; // Jump back to the label
}
return 0;
}In this example:
- We define a label called
loop_startusing a simple comment followed by a colon (:). - Inside the
mainfunction, we use agotostatement to jump back to theloop_startlabel as long as the conditioni < 5is true. - The program prints the values of
ifrom 0 to 4 in a loop.
It’s important to note that using goto and labels for control flow is generally discouraged in modern C programming because it can make code less readable and harder to maintain. Instead, you should use structured programming constructs like for, while, and do-while loops and conditionals (if, else) to control the flow of your program. These constructs are more idiomatic in C and are considered safer and more maintainable than using goto.
Here’s an example of the same loop without goto:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}This code accomplishes the same task but is more readable and follows the recommended programming style.