Goto Statement

Unconditional jump (and why to avoid it)

Interview Relevant: Understanding legacy code

Goto Statement

goto provides unconditional jumps to labeled statements.

Why Avoid goto

  • Makes code harder to read and maintain
  • Creates "spaghetti code"
  • Can skip variable initializations
  • Modern constructs (loops, functions) are clearer

Acceptable Uses

  • Breaking out of deeply nested loops
  • Cleanup code in C-style error handling

Code Examples

Goto usage and better alternatives.

cpp
1// Basic goto (avoid this pattern)
2int i = 0;
3loop_start:
4    cout << i << " ";
5    i++;
6    if (i < 5) goto loop_start;
7
8// Breaking from nested loops (one valid use case)
9for (int i = 0; i < 10; i++) {
10    for (int j = 0; j < 10; j++) {
11        if (matrix[i][j] == target) {
12            cout << "Found at " << i << "," << j << endl;
13            goto found;
14        }
15    }
16}
17cout << "Not found" << endl;
18goto end;
19found:
20    cout << "Processing found element" << endl;
21end:
22    // Continue with rest of code
23
24// Better alternative: use a flag or function
25bool searchMatrix(const vector<vector<int>>& matrix, int target) {
26    for (const auto& row : matrix) {
27        for (int val : row) {
28            if (val == target) return true;
29        }
30    }
31    return false;
32}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In