C Programming · November 18, 2026

The goto Statement in C: Jumping Around Your Program

Module I · Decision and Case Control · goto Statement (Unconditional Jump)


🎯 Why This Matters

Every program we have written so far runs from top to bottom. With if, switch and loops we learned to skip some lines or repeat others. C also has a much more direct tool for changing the flow: the goto statement. It says, “stop here and continue from that label instead”.

goto is the oldest control statement in programming, and also the most controversial. Many teachers tell students to avoid it completely, yet you will meet it in real code (the Linux kernel uses it thousands of times). So the goal of this post is twofold: to learn how it works, and to learn when it helps and when it hurts.

1️⃣ Syntax: goto and Labels

A goto always needs two parts: the jump itself and the place to jump to, called a label.

goto label_name;      // the jump

label_name:           // the destination (note the colon)
    statement;
  • A label is any valid identifier followed by a colon (:). The naming rules are the same as for variables.
  • The label must be inside the same function as the goto. Here that always means inside main().
  • The label may be after the goto (a forward jump) or before it (a backward jump).
  • A label must be followed by a statement. If you have nothing to put there, use an empty statement: a lone ;.

2️⃣ Forward Jump: Skipping Code

When the label comes below the goto, all the lines in between are skipped.

Figure 1: A forward jump skips the lines between the goto and its label.

Figure 1: A forward jump skips the lines between the goto and its label.

Example 1: Your First goto

#include <stdio.h>

int main() {
    printf("A\n");
    goto end;
    printf("B\n");      // skipped
    printf("C\n");      // skipped
end:
    printf("D\n");
    return 0;
}

🖥️ Output:
A
D

The program prints A, then meets goto end; and jumps straight to the label end:. The lines that print B and C are never executed. Execution then continues normally from the label.

Example 2: Skipping with a Condition

A plain goto always jumps. Combined with if it jumps only when something is true, which is far more useful.

#include <stdio.h>

int main() {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age < 18) {
        goto not_eligible;
    }

    printf("You can vote.\n");
    goto finish;

not_eligible:
    printf("Sorry, you cannot vote yet.\n");

finish:
    printf("Thank you!\n");
    return 0;
}

🖥️ Output:
Enter your age: 25
You can vote.
Thank you!

Age 25 is not below 18, so the goto not_eligible is ignored. The program prints “You can vote”, and then goto finish jumps over the “Sorry” message. Run it again with a different input:

#include <stdio.h>

int main() {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age < 18) {
        goto not_eligible;
    }

    printf("You can vote.\n");
    goto finish;

not_eligible:
    printf("Sorry, you cannot vote yet.\n");

finish:
    printf("Thank you!\n");
    return 0;
}

🖥️ Output:
Enter your age: 15
Sorry, you cannot vote yet.
Thank you!

Now the condition is true, so the program jumps straight to not_eligible.

💡 Why do we need the second goto finish;? Without it, after printing “You can vote” the program would simply keep falling down into the not_eligible section as well. A label is just a name for a line. It does not stop the flow.

Example 3: Even or Odd with goto

#include <stdio.h>

int main() {
    int n = 7;

    if (n % 2 == 0) goto even;

    printf("%d is odd\n", n);
    goto end;

even:
    printf("%d is even\n", n);

end:
    return 0;
}

🖥️ Output:
7 is odd

This works, but compare it with an ordinary if-else: it is longer and harder to read. This is a first hint that goto is not always the best tool.

3️⃣ Backward Jump: Building a Loop

When the label comes above the goto, the program goes back and repeats the lines in between. This is exactly what a loop does, so we can build a loop using only if and goto.

Figure 2: A backward jump repeats code, which is how a loop works.

Figure 2: A backward jump repeats code, which is how a loop works.

Example 4: Printing 1 to 5

#include <stdio.h>

int main() {
    int i = 1;

again:
    printf("%d ", i);
    i++;
    if (i <= 5) {
        goto again;
    }
    printf("\nDone\n");
    return 0;
}

🖥️ Output:
1 2 3 4 5
Done

🔍 Trace:
i = 1 → print 1 → i becomes 2 → 2 <= 5, so jump back
i = 2 → print 2 → i becomes 3 → jump back
… i = 5 → print 5 → i becomes 6 → 6 <= 5 is false, no jump
The program carries on to print “Done”.

Every loop needs the same three ingredients, even when it is made from goto: a starting value (i = 1), a change (i++) and a condition to keep going (i <= 5).

Example 5: Sum of 1 to N

#include <stdio.h>

int main() {
    int n = 5, i = 1, sum = 0;

repeat:
    sum = sum + i;
    i++;
    if (i <= n) {
        goto repeat;
    }

    printf("Sum of 1 to %d = %d\n", n, sum);
    return 0;
}

🖥️ Output:
Sum of 1 to 5 = 15

Example 6: Countdown

#include <stdio.h>

int main() {
    int n = 5;

loop:
    printf("%d\n", n);
    n--;
    if (n > 0) {
        goto loop;
    }

    printf("Lift off!\n");
    return 0;
}

🖥️ Output:
5
4
3
2
1
Lift off!

Example 7: Factorial

#include <stdio.h>

int main() {
    int n = 5, i = 1;
    long long fact = 1;

next:
    fact = fact * i;
    i++;
    if (i <= n) {
        goto next;
    }

    printf("%d! = %lld\n", n, fact);
    return 0;
}

🖥️ Output:
5! = 120

The result 5! = 5 × 4 × 3 × 2 × 1 = 120 is accumulated in fact. We used long long so that bigger factorials also fit.

Example 8: A Multiplication Table

#include <stdio.h>

int main() {
    int n = 7, i = 1;

line:
    printf("%d x %2d = %d\n", n, i, n * i);
    i++;
    if (i <= 5) {
        goto line;
    }
    return 0;
}

🖥️ Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

The Same Loop, Written Properly

Here is Example 4 written with a while loop. It gives the same result.

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    printf("\n");
    return 0;
}

🖥️ Output:
1 2 3 4 5

📊 Compare: the while version needs no label, the loop condition is written right at the top, and the body is clearly marked by curly brackets. With goto, the reader has to hunt for the label and for the jump to understand where the loop begins and ends. This is why structured loops (for, while, do-while) are preferred for ordinary repetition.

4️⃣ Practical Uses of goto

If loops are better written with for and while, is there any reason to use goto at all? Yes, in a few situations where it is actually the cleanest option.

Use 1: Retrying an Input

If the user types something invalid, we jump back to the question and ask again.

#include <stdio.h>

int main() {
    int marks;

ask:
    printf("Enter marks (0 to 100): ");
    scanf("%d", &marks);

    if (marks < 0 || marks > 100) {
        printf("Invalid! Try again.\n");
        goto ask;
    }

    printf("Marks accepted: %d\n", marks);
    return 0;
}

🖥️ Output:
Enter marks (0 to 100): 150
Invalid! Try again.
Enter marks (0 to 100): -5
Invalid! Try again.
Enter marks (0 to 100): 82
Marks accepted: 82

The first two answers (150 and -5) are out of range, so each time the program jumps back to the label ask. The third answer is valid and the program moves on.

Use 2: A Simple Repeating Menu

#include <stdio.h>

int main() {
    int choice;

menu:
    printf("\n1. Say Hello\n2. Say Bye\n3. Exit\nChoice: ");
    scanf("%d", &choice);

    if (choice == 1) {
        printf("Hello!\n");
        goto menu;
    }
    if (choice == 2) {
        printf("Bye!\n");
        goto menu;
    }
    if (choice != 3) {
        printf("Wrong choice.\n");
        goto menu;
    }

    printf("Exiting...\n");
    return 0;
}

🖥️ Output:

1. Say Hello
2. Say Bye
3. Exit
Choice: 1
Hello!

1. Say Hello
2. Say Bye
3. Exit
Choice: 2
Bye!

1. Say Hello
2. Say Bye
3. Exit
Choice: 9
Wrong choice.

1. Say Hello
2. Say Bye
3. Exit
Choice: 3
Exiting…

After every choice other than 3, the program jumps back to the menu. Choosing 3 is the only way to reach the end. (A switch inside a while loop is the more usual way to write this, but this version shows the idea clearly.)

Use 3: Escaping from Nested Loops

This is the most respected use of goto. The break statement leaves only the innermost loop. Let us see the problem first:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (j == 2) {
                break;              // leaves only the inner loop
            }
            printf("i=%d j=%d\n", i, j);
        }
    }
    return 0;
}

🖥️ Output:
i=1 j=1
i=2 j=1
i=3 j=1

Each time j reaches 2, break ends only the inner loop, and the outer loop goes on to the next i. What if we want to stop both loops at once? A goto can jump out of any number of loops in one step.

Figure 3: break leaves one loop, while goto can leave several loops at once.

Figure 3: break leaves one loop, while goto can leave several loops at once.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i == 2 && j == 2) {
                goto done;          // leaves BOTH loops
            }
            printf("i=%d j=%d\n", i, j);
        }
    }

done:
    printf("Loops finished\n");
    return 0;
}

🖥️ Output:
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
Loops finished

When i is 2 and j is 2, the goto done jumps beyond both loops. Without goto you would need an extra “found” flag variable and extra checks in both loops.

Example 9: Searching a 2-D Array

A typical real use. As soon as we find the key, we have no reason to continue looking, so we jump out of both loops.

#include <stdio.h>

int main() {
    int a[3][3] = {{4, 8, 1}, {7, 9, 3}, {5, 2, 6}};
    int key = 9;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (a[i][j] == key) {
                printf("Found %d at row %d, column %d\n", key, i, j);
                goto end;
            }
        }
    }
    printf("%d not found\n", key);

end:
    return 0;
}

🖥️ Output:
Found 9 at row 1, column 1

If the key is not in the array, both loops finish normally, and the “not found” message is printed instead:

#include <stdio.h>

int main() {
    int a[3][3] = {{4, 8, 1}, {7, 9, 3}, {5, 2, 6}};
    int key = 20;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (a[i][j] == key) {
                printf("Found %d at row %d, column %d\n", key, i, j);
                goto end;
            }
        }
    }
    printf("%d not found\n", key);

end:
    return 0;
}

🖥️ Output:
20 not found

In the first run, the goto end also skips the “not found” message. In the second run, nothing was found, so the program reaches that message naturally.

Example 10: A Prime Number Check

Checking divisors one by one: as soon as we find a divisor, we know the answer and can jump.

#include <stdio.h>

int main() {
    int n = 29;

    if (n < 2) goto not_prime;

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            goto not_prime;
        }
    }

    printf("%d is prime\n", n);
    return 0;

not_prime:
    printf("%d is not prime\n", n);
    return 0;
}

🖥️ Output:
29 is prime

Another number:

#include <stdio.h>

int main() {
    int n = 91;

    if (n < 2) goto not_prime;

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            goto not_prime;
        }
    }

    printf("%d is prime\n", n);
    return 0;

not_prime:
    printf("%d is not prime\n", n);
    return 0;
}

🖥️ Output:
91 is not prime

91 = 7 × 13, so the loop finds the divisor 7 and jumps to not_prime immediately.

Use 4: One Place to Handle Errors

When a program has several checks and any failed check should produce the same error message, goto avoids repeating that code in every check.

Figure 4: Several checks jump to one shared error handler.

Figure 4: Several checks jump to one shared error handler.

#include <stdio.h>

int main() {
    int age, marks;

    printf("Enter age and marks: ");
    scanf("%d %d", &age, &marks);

    if (age < 17 || age > 30) goto error;
    if (marks < 0 || marks > 100) goto error;
    if (marks < 40) goto error;

    printf("Admission form accepted.\n");
    return 0;

error:
    printf("Invalid or ineligible details.\n");
    return 1;
}

🖥️ Output:
Enter age and marks: 20 75
Admission form accepted.

With invalid or ineligible details, any one of the three checks jumps to error:

#include <stdio.h>

int main() {
    int age, marks;

    printf("Enter age and marks: ");
    scanf("%d %d", &age, &marks);

    if (age < 17 || age > 30) goto error;
    if (marks < 0 || marks > 100) goto error;
    if (marks < 40) goto error;

    printf("Admission form accepted.\n");
    return 0;

error:
    printf("Invalid or ineligible details.\n");
    return 1;
}

🖥️ Output:
Enter age and marks: 20 35
Invalid or ineligible details.

Age 20 passes the first two checks, but marks 35 are below the pass mark of 40, so the third check jumps to the shared error label. Note that return 1; signals to the operating system that the program ended with a problem, while return 0; means success.

5️⃣ Rules and Behaviour of goto

  • Same function only. You cannot jump from one function into another. Since we only have main() for now, this is automatically satisfied.
  • Labels need unique names within a function. Two labels called end: in the same function will not compile.
  • A label is not a barrier. If execution reaches a label by normal flow (without a jump), it simply continues past it.
  • A label must be followed by a statement. To label the very end of a block, write a lone ; after it.
  • Jumping out of loops and blocks is fine. Jumping into a loop or past a variable declaration is legal in some cases but dangerous, and is best avoided.
  • Labels have their own namespace. A label can have the same name as a variable without conflict, but you should not do this since it confuses readers.

Example 11: Label Followed by an Empty Statement

#include <stdio.h>

int main() {
    int count = 0;

start:
    count++;
    printf("Pass %d\n", count);
    if (count < 3) goto start;

    goto last;
last:
    ;                         // a label must be followed by a statement
    printf("Finished\n");
    return 0;
}

🖥️ Output:
Pass 1
Pass 2
Pass 3
Finished

Here the label last: is followed by ; (an empty statement) and then the real code. In older C standards, a label directly before a closing brace } would not compile, and the lone semicolon was the standard fix.

6️⃣ Why Do People Say “Avoid goto”?

In 1968 the computer scientist Edsger Dijkstra wrote a famous letter titled “Go To Statement Considered Harmful”. His point: programs full of jumps are very hard to follow. They are called spaghetti code because the flow is tangled like a plate of spaghetti.

Example 12: A Small Taste of Spaghetti

Try to predict the output of this program before reading the answer. It is only 8 lines of logic.

#include <stdio.h>

int main() {
    int x = 1;

    printf("a ");
    if (x == 1) { x = 2; goto c; }
b:  printf("b ");
    goto d;
c:  printf("c ");
    goto b;
d:  printf("d\n");
    return 0;
}

🖥️ Output:
a c b d

🔍 Trace:
Print a. Since x == 1, set x = 2 and jump to c.
At c: print c, then jump to b.
At b: print b, then jump to d.
At d: print d. The order printed is a c b d, even though the lines are written in the order a, b, c, d.

Even in this tiny program, you had to follow the path with your finger. Now imagine 500 lines of this. Bugs become very hard to find, and changing one part may break another. That is the real danger.

goto vs Structured Statements

TaskBetter choiceWhy
Repeat a known number of timesforStart, condition and change are all in one line
Repeat while a condition is truewhile / do-whileCondition is visible at the top (or bottom)
Leave one loop earlybreakClear, local meaning
Skip to the next iterationcontinueClear, local meaning
Choose one of several optionsif-else / switchEach branch is a visible block
Leave several nested loops at oncegotoThe only direct way (the alternative is extra flag variables)
Jump to a single error handler from many placesgotoAvoids repeating the same cleanup code

Guidelines for Using goto Sensibly

  1. Prefer for, while, if, break and continue whenever they can do the job.
  2. If you do use goto, jump forward (to an exit or error label) far more often than backward.
  3. Give labels meaningful names: error, done, not_prime, not l1 or x.
  4. Keep the jump short: the label should be close enough that the reader sees both on one screen.
  5. Never make the goto and its label cross each other in a tangle (a jump into the middle of another jump’s path).

🚫 Common Mistakes

Mistake 1: Forgetting the Colon After the Label

goto end;
...
end              // ❌ missing colon: error
    printf("Done");

end:             // ✅ correct
    printf("Done");

Mistake 2: Using an Undefined Label

goto finsh;      // ❌ typo: there is no label called finsh
...
finish:
    printf("Done");

The compiler reports “label ‘finsh’ used but not defined”. Spelling must match exactly, including upper and lower case.

Mistake 3: An Infinite Loop

int i = 1;
again:
    printf("%d ", i);
    goto again;      // ❌ nothing ever changes i or stops the jumping

A backward goto without a condition repeats forever. Always make sure that something inside the loop changes the condition, and that the jump is guarded by an if.

Mistake 4: Forgetting to Skip a Section

As seen in Example 2, a label does not stop the flow. If you want to avoid falling into a section, you must jump over it (with another goto) or end the program before it (with return).

Mistake 5: Jumping Out of a Function

// A goto in one function cannot jump to a label in another function.

A label belongs to the function in which it is written. For jumping between functions, C uses function calls and returns, which you will study later in the course.

🎓 Practice Exercises

Exercise 1: Predict the Output

printf("1 ");
goto L;
printf("2 ");
L:  printf("3");

(Answer: 1 3. The statement printing 2 is jumped over.)

Exercise 2: Predict the Output

int i = 0;
top:
    i += 2;
    printf("%d ", i);
    if (i < 7) goto top;

(Answer: 2 4 6 8 . The values are 2, 4, 6 and 8. When i is 6, the condition 6 < 7 is still true, so the loop runs once more and prints 8. Then 8 < 7 is false.)

Exercise 3: Predict the Output

int n = 3, f = 1;
again:
    f = f * n;
    n--;
    if (n > 0) goto again;
printf("%d", f);

(Answer: 6. It computes 3 × 2 × 1.)

Exercise 4: Nested Loops

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i * j == 4) goto out;
        printf("%d ", i * j);
    }
}
out:
    printf("end");

(Answer: 1 2 3 2 end. For i = 1 it prints 1 2 3. For i = 2 it prints 2, and then at j = 2 the product is 4, so it jumps to out, leaving both loops.)

Exercise 5: Build It Yourself

  1. Print the even numbers from 2 to 20 using only if and goto (no loop statements).
  2. Ask the user for a positive number. If they type zero or a negative number, keep asking again using goto.
  3. Write the “sum of 1 to N” program twice: once with goto and once with for. Which is easier to read?
  4. Search a 3×3 array for the first negative number. Use goto to leave both loops as soon as it is found.
  5. Rewrite Example 12 (the spaghetti program) with no goto at all, so that it prints a c b d in the same order.

❓ Frequently Asked Questions

Q: Is goto allowed in C, or is it a bad practice only?
It is fully legal and part of the language. “Bad practice” comes from overusing it for things that loops and if do better.

Q: Can goto replace all loops?
Yes. An if plus a backward goto can do whatever a for, while or do-while does. That is also why structured loops were invented: to give the same power in a safer, tidier form.

Q: What is the difference between break and goto?
break can only leave the innermost loop or a switch. goto can jump almost anywhere inside the same function, including out of several loops at once.

Q: Can two gotos jump to the same label?
Yes, and it is a common pattern: many places can share one error: or done: label, as in Example 10 and the error-handling example.

Q: Does a label have to be written at the start of a line?
No, the position in the line does not matter. By convention labels are written at the left edge so that they stand out.

Q: Is goto slower than a loop?
No. A compiler turns every loop into jumps anyway. The difference is purely about how readable your code is.

✅ Key Takeaways

  • goto label; jumps unconditionally to the statement marked label:, which must be written with a colon and be inside the same function.
  • A forward jump skips code. A backward jump repeats code, so if plus goto can imitate any loop.
  • A label does not stop the flow. Code falls through it unless you jump over it or end the program.
  • For ordinary repetition and decisions, for, while, if, switch, break and continue are clearer and should be preferred.
  • Two uses are widely accepted: leaving several nested loops at once and jumping to one shared error or exit label.
  • Overusing goto produces spaghetti code, which is hard to read, test and maintain.
  • Always give labels meaningful names, and make sure every backward jump has something that eventually stops it.

🚀 Keep practising: Take any loop program from the earlier posts and rewrite it using if and goto. You will see for yourself what loops do behind the scenes, and why we are glad to have them.

All 29 lessons in this series (open course page)

Part 1 · Getting Started

Part 2 · Data Types, Input/Output and Operators

Part 3 · Decisions and Loops

Part 4 · Arrays

Part 5 · Strings

Part 6 · Functions and Scope

Part 7 · Pointers