C - Go to Statement
Overview
goto
performs an unconditional jump to a labeled statement. Use sparingly; structured control flow is usually clearer.
Learning Objectives
- Recognize when
goto
may be acceptable (e.g., error cleanup).
Prerequisites
Example
#include <stdio.h>
int main(void) {
int i = 0;
loop:
if (i < 3) { printf("%d\n", i++); goto loop; }
}
Checks for Understanding
- Why is
goto
discouraged in most cases?
Show answer
It can create spaghetti code that is hard to read and maintain.
Practical Example: Error handling and cleanup
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen("data.txt", "r");
char *buf = NULL;
if (!f) goto cleanup;
buf = malloc(1024);
if (!buf) goto cleanup;
// ... work with f and buf ...
cleanup:
if (buf) free(buf);
if (f) fclose(f);
return 0;
}
Expected Output: No output; resources are safely released on any path.
Common Pitfalls
- Jumping into a block can skip initializations (undefined behavior); only jump forward to labels in the same function.
- Overuse of
goto
harms readability—prefer structured control flow.
Exercises
- Open a file and allocate a buffer; ensure both are freed/closed using a single cleanup label.
- Simulate an error path and verify cleanup still occurs.