C goto Statement

The goto statement in C is used to transfer control to a specific label within a function. This statement can create a jump in the flow of execution, bypassing certain code segments. While it is a powerful tool, it is often discouraged in structured programming because it can make the code less readable and harder to follow.

1. goto Statement Syntax

The goto statement is followed by a label (a user-defined identifier), and the control is transferred to that label when the goto statement is executed.

Syntax:

                        
goto label_name;
        
// Label declaration
    label_name:
// Code to be executed after jump
                        
                    

Example:

                        
#include <stdio.h>
int main() 
{
   int i = 0;
            
   start:
       if (i >= 5) {
            goto end;  // Jump to the 'end' label if i >= 5
        }
                
        printf("%d\n", i);
        i++;
        goto start;  // Jump back to the 'start' label for next iteration
            
            end:
                return 0;
}
                        
                    

Output:

0
1
2
3
4

2. Key Points of the goto Statement

3. When to Use the goto Statement

4. Example of goto in Error Handling

The following example demonstrates the use of goto for error handling. If an error occurs during the program's execution, the program will jump to the error handling block.

                        
#include <stdio.h>
int main()
{
    int success = 0; // 0 indicates failure, 1 indicates success
        
    if (success == 0) {
        printf("Error occurred. Jumping to error handler.\n");
        goto error_handler; // Jump to error handler if failure
      }
        
    // Normal execution
    printf("Program executed successfully.\n");
        
    error_handler:
        printf("Handling error...\n");
        return 1;
}
                        
                    

Output:

Error occurred. Jumping to error handler.
Handling error...

5. Key Considerations