13 February 2009

goto

- A goto statement causes your program to unconditionally transfer control to the statement associated with the label specified on the goto staement.

- Because the goto statement can interfere with the normal sequence of processing, it makes a program more difficult and maintain. Often, a break statement, a continue statement, or a function call can eliminate the need for a goto statement.

- If an active block is exited using the goto statement, any local variables are destroyed when the control is transferred from that block.

- Also , one cannot use a goto statement to jump over initializations.

- A goto statement is allowed to jump within the scope of a variable length array, but not past any declaration of objects with variably modified types.

goto name1;
/* name1 is the identifier for the jumping location */
/* name1 is a valid variable followed by colon */

…………. ………….
…………. ………….
…………. ………….
name1: Statement;



Eversince I started writing C codes (which is more than a decade back) I have been instructed not to use the keyword 'goto' ever. and I were to say that we all have been doing a goto-less programming then it would not be out of place. Infact, goto is much like a contradiction to the philosophy of C. C follows a structured instruction flow, and use of goto makes it break that flow and starts jumping the code sequence.

The inclusion of goto in the ANSI C itself shows that it has some utility in the programming, and should be used whenever and wherever required. The most common use of goto statements is when you need to jump out of multiple loops for a safe landing, and it is expected that it should not be used for jumping out of single loops. Instead, whenever we encounter multiple loops, say 3 or 4, we need to use goto.

Having said that goto is the most efficient code line when we need to jump out of multiple loops, it is also a must to know that the landing code should not be with-in a loop (or a loop with-in a loop).

An example of such a code using goto is here :

#include
void display(int matrix[3][3]);

int main(void)
{
int matrix[3][3]= {1,2,3,4,5,2,8,9,10};
display(matrix);
return(0);
}

void display(int matrix[3][3])
{
int i, j;

for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
{
if ( (matrix[i][j] < 1) || (matrix[i][j] > 6) )
goto out_of_bounds;
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
return;
out_of_bounds: printf("number must be 1 through 6\n");
}


And finally here are some interesting facts against goto statements.......

1. MATLAB does not have goto at all, and it sometimes make programming so much difficult without it.

2. Java has a reserved keyword as goto, but does not define its syntax.

3. Dijkstra's letter against goto : http://www.cs.ubbcluj.ro/~adriana/FP/Requirements/dijkstra68goto.pdf