Goto Statement in C Programming Guide
In the C language, the goto statement can be used to jump to any location in the program. The basic syntax of the goto statement is as follows:
goto label;
Here, a label is a tag, typically consisting of an identifier followed by a colon (:). When using the goto statement, the program will jump to the specified label to execute the code.
Here is a simple example demonstrating how to use the goto statement:
#include <stdio.h>
int main() {
int number;
input:
printf("请输入一个正整数:");
scanf("%d", &number);
if (number <= 0) {
printf("输入无效,请重新输入\n");
goto input;
}
printf("您输入的数字为:%d\n", number);
return 0;
}
In this example, when a user inputs a number less than or equal to 0, an error message will be displayed and the program will use a goto statement to jump back to the input prompt for the user to re-enter a valid number. This approach helps avoid using nested loop structures, making the code more concise. However, goto statements can lead to confusion and reduce the readability of the program, so it is recommended to minimize the use of goto statements in actual development.