Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

The goto statement

C Programming Language goto statement
The goto statement is used to transfer (jump) program control from one part to another part directly.

Syntax

goto label;
    statement1;
    ----------
label:
    ----------
    statementN;

Working

C Programming Language goto statement Working

Example

#include<stdio.h>
int main()
{
    printf(" Before goto statement");
	
    goto destination3;
    printf("\n before destinations");
	     
    destination1 :
        printf("\n control at destination1");
    destination2 :
        printf("\n control at destination2");
    destination3 :
        printf("\n control at destination3");
    destination4 :
        printf("\n control at destination4");
		
    printf("\n After destinations");
    return 0;
}

Output

Before goto statement
control at destination3
control at destination4
After destinations

In the above program, statements between goto & label (destination3) are skipped.

Example

#include<stdio.h>
int main()
{
    printf(" Before goto statement");

    goto destination3;
            printf("\n before destinations");
	     
    destination1 :
	    printf("\n control at destination1");
    destination2 :
	    printf("\n control at destination2");
    destination3 :
	    printf("\n control at destination3");
	    goto last;
    destination4 :
	    printf("\n control at destination4");
		
    printf("\n After destinations");
	
    last:
           ;
	
    return 0;
}

Output

Before goto statement
control at destination3

Condition similar to infinite loop using goto statement

#include <stdio.h>
int main()
{
    printf(" Before goto statement");
	
    goto destination3;
	    printf("\n before destinations");
	     
    destination1 :
	    printf("\n control at destination1");
    destination2 :
	    printf("\n control at destination2");
    destination3 :
	    printf("\n control at destination3");
	    goto destination1;
    destination4 :
	    printf("\n control at destination4");
	 	
    printf("\n After destinations");
    return 0;
}

Here statements of label destination1, destination2 & destination3 executes repeatedly & infinitely.

Note

The goto statement is used very rarely. Because using goto makes difficult to trace the flow of program control.
A good programmer tries to avoid the use of goto statement mostly.

 

Leave a reply