THE goto STATEMENT

The goto statement is used to alter the normal sequence of program instructions by transferring the control to some other portion of the program .The syntax is as follows:

goto label;

Here,label is an identifier that is used to label the statement to which control will be transferred.The targeted statement  must be preceded by the unique label followed by colon.

label : statement ;

Although goto statement is used to alter the normal sequence of program  execution but its usage in the program should be avoided.The most common application are:

1)To branch  around statements under certain conditions in place of use of if-else statement .

2)To jump to the end of the loop under certain  conditions by passing the rest of the statements inside the loop in place of continue statement.

3)To jump out of the loop avoiding the use of break statement.

goto can never be used to jump into the loop from outside and it should be preferably used for forward jump.

Situations may arise,however,in which the goto statement can be useful.To the possible extent,the use of the goto statement should generally be avoided.




EXAMPLE

Write a program to print first 10 even numbers.

#include<stdio.h>
main(){
int i=2;
while(i)
 {
printf("%d",i);
i=i+2;
if(i>=20)
goto outside;
}
outside:printf("over")
}

OUTPUT
2 4 6 8 10 12 14 16 18 20 over

0 comments:

Post a Comment