Goto statement in C

Goto statement in c, is used to transfer the control to some other part of the program unconditionally. It will change the order of statements execution.

Goto statement is used to alter the normal sequence of program execution.

It is written as :

goto label;
Where the ‘goto’ is a keyword and ‘label; is an identifier. The label is the target statement to which the control is transferred. Thus the target statement will appear as label: statement;

The following program illustrates the use :
void main()
{
int i=10, j=50;
printf(“\n printing value of i and j”);
goto Test1;
Test1: printf(“\n printing value of i=%d”,i);
goto Test2;
Test2: printf(“\n printing value of j=%d”,j);
}
Output:
printing value of i and j
printing value of i=10
printing value of j=50

Thumb Rule to use goto statement in c -;
• Each labeled statement within the function must have a unique label, i.e., no two statements can have the same label.

• The execution may lead to infinite loop.

For example if above program is written like:
void main()
{
int i=10, j=50;
printf(“\n printing value of i and j”);
goto Test1;
Test2: printf(“\n printing value of j=%d”,j);
Test1: printf(“\n printing value of i=%d”,i);
goto Test2;
}

Advantage of Goto Statement
– Used to alter the normal sequence of the program execution
– Gives power to jump to any part of program

Types of Goto statement
1. Forward jump
2. Backward jump

Leave a Reply