C++ 在不同的函数中使用 Goto 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17357199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Goto function across different functions
提问by Bhushanam Bhargav
How can I use goto function across different functions .For ex ,
如何在不同的功能中使用 goto 功能。例如,
main()
{
....
REACH:
......
}
void function()
{
goto REACH ;
}
How to implement such usage ?
如何实现这种用法?
回答by Captain Obvlious
You can't in Standard C++. From $6.6.4/1 of the C++ Language Standard
你不能在标准 C++ 中。从 C++ 语言标准 6.6.4/1 美元起
The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function.
goto 语句无条件地将控制转移到由标识符标记的语句。标识符应是位于当前函数中的标签(6.1)。
...or in Standard C. From $6.8.6.1/1 of the C Language Standard
...或标准 C。从 C 语言标准的 6.8.6.1/1 美元起
The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.
goto 语句中的标识符应命名位于封闭函数中某处的标签。goto 语句不应从具有可变修改类型的标识符的范围之外跳转到该标识符的范围内。
回答by Jonathan Leffler
回答by Andrio Skur
For gcc:
对于 gcc:
#include <iostream>
void func(void* target){
std::cout << "func" <<std::endl;
goto *target;
}
int main() {
void* target;
auto flag = true;
l:
std::cout << "label" <<std::endl;
target = &&l;
if (flag) {
flag = false;
func(target);
}
}
Note that this can be an undefined behavior
请注意,这可能是未定义的行为
回答by Rishabh Jain
You can't. Think of this. There is a function A which is recursively calling another function B which in turn is calling A. Now, suppose that you put a goto statement from A to B. The question now becomes which instance of A do you want to go to which is undefined. Also, if no previous instance of A is defined, you have a bigger problem of no initialized variables in the function that are present before the label.
你不能。想想这个。有一个函数 A 递归地调用另一个函数 B,后者又调用 A。现在,假设您将 goto 语句从 A 放到 B 中。现在的问题变成了您想要转到哪个 A 实例未定义. 此外,如果之前没有定义 A 的实例,则会遇到更大的问题,即函数中没有出现在标签之前的初始化变量。
#include "bits/stdc++.h"
int i=0;
A(){
run:
B();
}
B(){
if(i==10)
goto run;
i++;
A();
}