goto statement
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
将控制转移到一个新的位置
时使用的,否则不可能将控制转移到所需的位置,采用传统的结构.
原文:
Used when it is otherwise impossible to transfer control to the desired location using conventional constructs.
目录 |
[编辑] 语法
goto label
|
|||||||||
[编辑] 解释
goto语句将控制权转移的label指定的位置。goto语句必须在label是指相同的功能。如果goto语句将控制向后,所有尚未初始化的对象,在label破坏,这是非法转移控制的转发,如果这样做会跳过初始化一个对象.
原文:
The goto statement transfers control to the location specified by label. The goto statement must be in the same function as the label it is referring. If goto statement transfers control backwards, all objects that are not yet initialized at the label are destructed. It is illegal to transfer control forwards if doing so would skip initialization of an object.
[编辑] 关键字
[编辑] 示例
#include <iostream> struct Object { ~Object() { std::cout << "d"; } }; int main() { int a = 10; //loop using goto label: Object obj; std::cout << a << " "; a = a - 2; if (a != 0) { goto label; //causes obj to be destructed } std::cout << '\n'; //get out of 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'; return 0; //causes obj to be destructed }
输出:
10 d8 d6 d4 d2 (0;0) (0;1) (0;2) (1;0) (1;1) (1;2) d