The goto statement in C is indeed used to transfer control to a specific part of the program marked by a label. While it can be useful in some situations, it is generally advised to use it sparingly due to potential issues with readability and maintainability.
label:
// some part of the code
goto label;
A label is defined by a name followed by a colon (:). It serves as a target for the goto statement.
The goto statement is used to jump to the label specified. Execution resumes from the point of the label.
#include <stdio.h>
int main() {
int count = 0;
start: // Label definition
if (count < 5) {
printf("Count is %d\\n", count);
count++;
goto start; // Jump to the 'start' label
}
printf("Loop terminated.\\n");
return 0;
}
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop terminated.
Simple Control Flow: In some cases, goto can simplify complex control flows, especially in error handling or breaking out of deeply nested loops.
Readability: Overuse of goto can make code difficult to follow, as it breaks the linear flow of control.
Maintenance: It can lead to code that is hard to maintain and debug.
• Loops: For repeated actions, use loops (for, while, do-while).
• Functions: For structured control flow and reusability, use functions.
• Break/Continue: Use break and continue to control loop execution more clearly.