Types of goto Statements -Programmer's Mind

Unconditional control statements in C are goto,break,continue.

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:


forward goto program

In above program printf statement after goto will be skipped and compiler generates a warning "Unreachable Code".

    forward goto program

Output will be as follows:

    forward goto program

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:

backward goto program

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:

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.

Related topics:

Previous topic:

Next topic:

Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment