c++ goto 语句的使用
在c语言中,限制较小,goto语句除开不能跳转到可变长数组、可修改指针这类变量所在的作用域scope;能够跳转到其他所有变量的作用域(原因:struct中没有类这个概念)
在c++中 1.1. 向前跳转:跳出变量的作用域
label:
Object obj;
int d;
std::cout << a << " ";
a = a - 2;
if (a != 0) {
goto label; // jumps out of scope of obj, calls obj destructor召唤lable~goto
//lable范围内,所有变量的析构函:{POD类型(c语言基本变量类型的析构函数是trival-dctor,没有意义的细狗函数)
}
1.2.向后跳转:跳转到某些变量的作用域
-
scalar types declared without initializers :如int a=4,错;int a;
-
class types with trivial default constructors and trivial destructors declared without initializers :即使类对象中不能有显式构造、析构函数。注明:如果类成员中,有一些变量,如开辟了内存,定义了指针,则一定要定义显式析构函数,否则内存泄漏。
-
cv-qualified versions of one of the above 可在运行期间被修改和源代码中被修改的上述类型变量
-
arrays of one of the above (Note: the same rules apply to all forms of transfer of control)
std::cout << '\n';
// goto can be used to leave a multi-level loop easily
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
std::cout << "(" << x << ";" << y << ") " << '\n';
if (x + y >= 3) {
goto endloop;
}
}
}
endloop:
std::cout << '\n';
goto label2; // jumps into the scope of n and t
int n; // no initializer
Trivial t; // trivial ctor/dtor, no initializer
// int x = 1; // error: has initializer
// Object obj2; // error: non-trivial dtor
label2:
{
Object obj3;
goto label3; // jumps forward, out of scope of obj3
}
label3:
std::cout << '\n';
}