This blog is under construction

Saturday, 21 April 2012

label and goto Statement

goto statement:
goto statement transfers control from one part of the program to another.  It is an unconditional jump(control transfer) statement.  Below is the syntax for goto statement.

Syntax:
goto label;
.......
label:

We have to specify label for goto statement.  When goto statement is executed, program control transfers to label.

What is a label?
Label is just an identifier followed by a colon.  Label is usually associated with goto statements and it used to identify where the control needs to be transferred while executing goto statement.

goto err;
.....
err:   // err is a label

Note:
Label name needs to be an unique identifier and there should be at least one statement next to label.

Example C program using goto and label:
 
   #include <stdio.h>
   int main() {
           int input, i, data[100], count;
           printf("Enter Positive integers alone as input:\n");
           for (i = 0; i < 100; i++) {
                   scanf("%d", &input);
                   if (input < 0)
                           goto err;

                   data[i] = input;
          }
          printf("All your inputs are positive values\n");
  err:
          count = i;
          printf("Outputs:\n");
          for (i = 0; i < count; i++)
                  printf("%d\n", data[i]);
          return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter Positive integers alone as input:
  1
  2
  3
  4
  -5
  Outputs:
  1
  2
  3
  4

Here the user has given -5 as his 5th input.  Since it is a negative integer value, goto statement is executed which in turn transfers program flow to the section of code below the label err.


1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete