C goto Statement

The goto statement jumps to a label in the same function. A label is a name followed by a colon.

Syntax and example

#include <stdio.h>

int main(void) {
    int i = 1;

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

    printf("End\n");
    return 0;
}

Output:

Output of the above program is

1
2
3
End

A fair use: leave nested loops

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i * j == 4) {
                printf("Found at i=%d j=%d\n", i, j);
                goto done;
            }
        }
    }
done:
    printf("Finished\n");
    return 0;
}

Output:

Output of the above program is

Found at i=2 j=2
Finished

Note: goto makes the program flow difficult to follow, so most programmers avoid it. Use loops and functions instead. The nested loop exit above is one of few places where it is accepted.

Next: C Functions.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to check whether a number is even or odd
Write a C program to check whether a user is eligible to vote or not
Write a C program to check whether an alphabet is vowel or consonant
Write a C program to find the maximum number between three numbers
Write a C program to check whether a number is positive, negative or zero
Write a C program to calculate an electricity bill
Write a C program to print 1 to 10 numbers using a while loop
Interview Questions & Answers
What is the difference between while and do while loop in C?
What is the difference between break and continue in C?
How to check if a number is prime in C?
How to find the factorial of a number in C?