Cover Image for Local Labels in C
96 views

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:

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_start using a simple comment followed by a colon (:).
  • Inside the main function, we use a goto statement to jump back to the loop_start label as long as the condition i < 5 is true.
  • The program prints the values of i from 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:

C
#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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS