A goto
statement provides the ability to jump to a named-label anywhere within the same function.
goto label; .. //some part of the code; label:
Let's see a simple example to use goto statement in C language.
#include <stdio.h> int main() { int num,i=1; printf("Enter the number whose table you want to print?"); scanf("%d",&num); table: printf("%d x %d = %d\n",num,i,num*i); i++; if(i<=10) goto table; }
A goto
can be useful is if it becomes necessary to break
out of a deeply nested structure, such as nested loops. A break
statement cannot do this as it can only break out of one level at a time. Consider the following example.
#include <stdio.h> int main() { int i, j, k; for(i=0;i<10;i++) { for(j=0;j<5;j++) { for(k=0;k<3;k++) { printf("%d %d %d\n",i,j,k); if(j == 3) { goto out; } } } } out: printf("came out of the loop"); }