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.
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
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.
No comments:
Post a Comment