Goto Statement in C

Level 5343 keystrokes

Uses goto for the common C cleanup pattern: if either of two allocations fails, the code jumps to a single cleanup label that frees whatever was allocated. Here both succeed, so it prints Allocation successful, Processing data... and Cleanup complete.

C code

// Both pointers start as NULL so the cleanup code can tell what was allocated
1int *data = NULL;
2int *buffer = NULL;
3
// First allocation: 10 ints
4data = (int *)malloc(sizeof(int) * 10);
// On failure, jumps straight to cleanup
5if (data == NULL) goto cleanup;
6
// Second allocation: 20 ints
7buffer = (int *)malloc(sizeof(int) * 20);
// On failure, cleanup must still free data, which is already allocated
8if (buffer == NULL) goto cleanup;
9
// Reached only when both allocations succeeded
10printf("Allocation successful\n");
11printf("Processing data...\n");
12
// The single exit point: normal flow also falls through into this label
13cleanup:
// Frees buffer only if it was allocated (free(NULL) would also be harmless)
14 if (buffer) free(buffer);
// The same check for data
15 if (data) free(data);
// Prints Cleanup complete
16 printf("Cleanup complete\n");

Output

Allocation successful
Processing data...
Cleanup complete
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • (× 15
  • )× 15
  • ;× 11
  • =× 8
  • "× 6
  • *× 6
  • .× 3
  • \× 3
  • :× 1

More C examples at level 5

← C typing practice