Sunday, July 14, 2013

The goto Statement in C

The goto Statement is an unconditional branching statement in C. Suppose if we want to go to some set of statements in the same function immediately. Then we use goto to switch from current executing statements to the block of statements which we want to perform and the execution continues from that lines of execution.

The goto statement must have a label. A label is that which recognizes which set of statements are to be executed. Consider the following example, to understand more about the  goto statement.

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a;
  5. start: ;
    1. printf("Enter a number between 0 and 10");
    2. scanf("%d", &a);
  6. if(a==1)
  7. goto one;
  8. else if(a>0&&a<10)
  9. goto all;
  10. else
  11. goto start;
  12.  
  13. one : ;
    1. printf("The number is one");
    2. goto end;
  14. all : ;
    1. printf("The number is not one");
    2. goto end;
  15. end: return 0;
  16. }
The above program best represents the goto statement. Check out the following explanation, to understand the program.

In the above program, we have taken a variable a and asking the user to enter a number between 0 and 10. If he enters any number which is not in the limit, then we goto start again for asking a number. If he enters a number between 0 and 10 and the number is 1, then we move on to label "one" which prints that the number is one, and then we move to end to end the program. If we don''t mention goto end, then the statements of the label "all" are also executed. If the number is not one, then we move to the section "all" where it prints out as "The number is not one". Thus we use a goto statement.

The label statement may be used after the goto statement or before the goto statement. If we use before, it turns to be a loop. So we should be careful in using the goto statement.

What is Spaghetti code? To know click here.