Virtual assistance Chat Bot

C Programming Tutorial

Welcome to AIVista --India's tutorial pages on C Programming

C Programming

Goto Statement in C

The goto statement allows an unconditional jump to a specified label within the same function.

"The goto statement provides an explicit jump, but use it wisely to avoid unstructured code."

What is the goto Statement?

The goto statement is used to transfer control to a labeled statement within the same function.

Syntax of goto

goto label;
...
label:
// Statements

How goto Works

  • A label is defined using an identifier followed by a colon (:).
  • The goto statement transfers program execution to the labeled statement.
  • Note: The label must be within the same function.

Example: Using goto for Conditional Jumps

#include <stdio.h>

int main() {
int num;
printf("Enter a positive number: ");
scanf("%d", &num);

if (num < 0) {
	goto error;
}

printf("You entered: %d\n", num);
return 0;

error:
printf("Error: Negative numbers are not allowed.\n");
return 1;
}

Types of Jumps Using goto

Type Description
Forward Jump Jumping ahead to a labeled statement.
Backward Jump Jumping back to a previously defined label.

Example: Forward Jump Using goto

#include <stdio.h>

int main() {
printf("Start of program\n");
goto skip;
printf("This line is skipped.\n");

skip:
printf("End of program\n");
return 0;
}

Example: Backward Jump Using goto

#include <stdio.h>

int main() {
int count = 1;

repeat:
printf("Count: %d\n", count);
count++;

if (count <= 5) {
	goto repeat;
}

return 0;
}

When to Use goto

  • When breaking out of deeply nested loops.
  • For error handling to jump to a cleanup section.
  • For improving readability in certain complex scenarios.

When to Avoid goto

  • When it creates "spaghetti code" that is hard to follow.
  • When structured alternatives (loops, functions, conditionals) can be used.
  • When it makes debugging more difficult.

Example: Using goto for Error Handling

#include <stdio.h>

int main() {
FILE *file = fopen("data.txt", "r");

if (file == NULL) {
	goto error;
}

printf("File opened successfully.\n");
fclose(file);
return 0;

error:
printf("Error: Could not open file.\n");
return 1;
}

Alternative to goto

Instead of goto, structured programming constructs like loops and functions should be used.

Using Loops Instead of goto

#include <stdio.h>

int main() {
for (int count = 1; count <= 5; count++) {
	printf("Count: %d\n", count);
}
return 0;
}

Best Practices for Using goto

  • Use it only when necessary (e.g., error handling, breaking multiple loops).
  • Keep labels meaningful and easy to follow.
  • Avoid excessive goto jumps within the same function.

Conclusion

The goto statement in C provides direct control over program flow, but it should be used carefully to maintain code readability and maintainability.