Syntax of goto statement -
goto point_x;
point_x:
statement;
goto is followed by something called as label, which is point_x here. Whenever goto is executed the execution jumps to label it is pointing at. The label are defined as label name followed by colon.
In the below diagram, in the left side, label occurs before current goto statement (ugly part), in right side, label occurs after the current goto statement (good part).
goto - before
If label is before the present goto statement then there is a possibility of the loop. Goto is never meant to be used as the loop. This is ugly part of goto. This has to be avoided at all cost, looping constructs like while, do while and for can easily replace them. Lets go through an example first and later see how it can be modified in better way.Program to find sum of first n number.
#include <stdio.h> int main() { int n = 10; int counter; int sum; counter = 1; sum = 0; sum_it: sum = sum + counter; if(counter < n) { counter++; goto sum_it; } printf("Sum is %d\n", sum); return 0; }
Output of above program is
Sum is 55
This type of goto usage should be never done. Here goto is producing a loop, which is hard to understand. It can be easily written without goto as follows.
#include <stdio.h> int main() { int n = 10; int counter; int sum = 0; for(counter = 1; counter <= n; counter++) { sum +=counter; } return 0; }
goto - after
It is basically done for error handling, Say following is pseudo code initializing computer hard ware.if(!init_mouse){
goto mouse_fail;
}
if(!init_keyboard){
goto keyboard_fail;
}
mouse_fail:
remove_mouse;
keyboard_fail:
remove_keyboard;
Something like that. Future there will be article called Error Handling which will be more practical example.
NOTE:
- goto cannot be used between two function. (Function will be covered later)
- goto can help come out of nested loops (while break can help in breaking only one loop).
Links
Quiz - Not written yetNext Article - C Programming #29: Constant Macros
Previous Article - C Programming #27: Loop - infinite
All Articles - C Programming
No comments :
Post a Comment