C goto statement
Created By: chatGPT
The goto statement in C is used to transfer control to a labeled statement within a function. Although it's sometimes seen as a tool of last resort due to its potential to lead to spaghetti code, it can be useful in certain scenarios, such as breaking out of deeply nested loops or handling error conditions. However, it’s crucial to use it judiciously to maintain program readability and structure.
#include <stdio.h>
int main() {
int i = 0;
loop:
printf("Value of i: %d\n", i);
if (i < 5) {
i++;
goto loop; // Jumps back to the loop label
}
printf("Finished looping!\n");
return 0;
}
In this example, the goto statement provides a way to repeat the loop until the condition is met (i.e., until i becomes 5). The label named loop marks the point in the code where execution returns when the goto loop statement is encountered. This approach avoids explicit loop constructs like
for
or while
, but it can make the flow of control less clear.int main() {
int result;
tryAgain:
printf("Enter a number less than 10: ");
scanf("%d", &result);
if (result >= 10) {
printf("Number is too high. Try again.\n");
goto tryAgain; // Jumps back to tryAgain label
}
printf("You entered: %d\n", result);
return 0;
}
In the second example, a goto statement is used to prompt the user until they enter a valid number (less than 10). The
tryAgain
label serves as a location to which control can jump if the user's input does not meet the specified condition. While this can simplify error handling in certain contexts, always consider using better control structures first to ensure clarity and maintainability.// Avoid using goto unless absolutely necessary!
#include <stdio.h>
int main() {
int num;
for (int i = 0; i < 5; i++) {
if (i == 3) {
goto skip;
}
printf("Value of i: %d\n", i);
}
skip:
printf("Skipped the value when i reached 3!\n");
return 0;
}