goto statement
The Goto
statement :-
C language supports "goto" statement to branch unconditionally from one point to another in the program.
C language supports "goto" statement to branch unconditionally from one point to another in the program.
The goto
requires a label in order to identify the place where the branch is to be made.
A label is any valid variable name, and must be followed by a colon. The label
is placed just before the statement where the control is to be
transferred.
The general forms of goto and label statements are:-
The general forms of goto and label statements are:-
While executing the program,when a statement like
"goto begin;" is met, the flow of control will jump to the statement
immediately following the label "begin:". A goto breaks the normal
sequencial execution of the program. If the "label:" is before the
statement "goto label;" a loop
will be formed and some statments will be executed repeatedly. Such a jump is
called backward jump. And, if the "label:" is placed after
the"goto label;", some statements will be skipped and the jump is
knwn as forward jump. "goto" statement is usually used at the end of
a program to direct the control to go to
the input statement, to read further data. Consider an example :-
main()
{
int x,y;
read:
scanf("%d", &x);
if
(x<0) goto read;
y =
sqrt(x);
printf("%d %d\n", x,y);
goto
read;
}
This program is written to evaluate the square
root of a series of numbers read from the terminal. The program uses two goto
statements, one at the end, after printing the results to transfer the control
back to the input statement and the other is to skip any further computation
when the number is negative. Due to unconditional goto statement at the end,
the control is always transferred back to the input statement. When the program
puts the comuter in a permanent loop, such situation is called as an
"infinite loop". In such situation, computer goes round and round
until we takes some special steps to terminate the loop. Another use of goto
statement is to transfer the control out of a loop when certain pecular
conditions are encountered. We should try to avoid using goto as much as
possible. But there is nothing wrong, if we use it to enhance the readability
of the program or to improve the execution speed.
Comments
Post a Comment