C++教程-C++的goto语句
C++的goto语句
C++的goto语句也被称为跳转语句。它用于将控制转移到程序的其他部分。它无条件地跳转到指定的标签。
它可以用于从深层嵌套的循环或switch语句标签中转移控制。
C++ goto语句示例:
让我们看一个C++中goto语句的简单例子。
#include <iostream>
using namespace std;
int main() {
ineligible:
cout << "You are not eligible to vote!\n";
cout << "Enter your age:\n";
int age;
cin >> age;
if (age < 18) {
goto ineligible;
} else {
cout << "You are eligible to vote!";
}
return 0;
}
输出:
You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!
请注意,使用goto语句可以使程序更难以理解和维护。在大多数情况下,应避免使用goto语句,并尽量使用更结构化和可读性更高的代码。