Unconditional control statements in C are goto,break,continue.
statement-2;
goto label;
statement-3;
.
.
.
.
statement-n;
label:
statements;
goto Statement:
goto statement cause some unconditional jumps in the execution of the program.Jump can be either forward jump or backward jump
Syntax for Forward goto:
statement-1;statement-2;
goto label;
statement-3;
.
.
.
.
statement-n;
label:
statements;
First the compiler executes the statements from statement-1 when it finds the goto statement then it searches for the label in the program and control transfers to the statements after that label.The statements between label and goto statement will be skipped.
Example Program for forward goto Statement:
In above program printf statement after goto will be skipped and compiler generates a warning "Unreachable Code".
Output will be as follows:
Backward goto
If the jump is to previous statements in the program then it is backward goto. Syntax for backward goto statement is
statement-1;
statement-2;
label:
statement-3;
.
.
.
.
statement-n;
goto label;
statements;
Program for using backward goto:
In above program printf statement after goto statement will not be executed hence unreachable code and this program results an infinite loop
Output of the Backward goto program:
Problems with goto:
While using backward goto we must take care to avoid infinite loop. The infinite loop formed by the backward goto is the major problem with goto statement. There is a chance to skip the important code while using goto.
0 comments:
Post a Comment