[英]How to use goto statement in lambda expression C++
Is there any way to use goto statement in lambda expression? 有没有办法在lambda表达式中使用goto语句?
#include <iostream>
int main()
{
auto lambda = []() {
goto label;
return;
};
lambda();
return 0;
label:
std::cout << "hello, world!" << std::endl;
}
I want the console to output hello, world!, but the compiler gives an error: 我希望控制台输出hello,world!,但编译器会出错:
use of undeclared label 'label'
goto label;
^
1 error generated.
Is there any way to use goto statement in lambda expression? 有没有办法在lambda表达式中使用goto语句?
No. Not to leave the scope of lambda and jump to the enclosing scope. 不。不要离开lambda的范围并跳转到封闭范围。 You can only goto
a labeled statement inside the lambda, same as if it were any other function. 您只能在lambda中goto
带标签的语句,就像它是任何其他函数一样。
Having said that, the uses for goto
in C++ specifically are few and infrequent. 话虽如此,C ++中goto
的使用特别少而且不常见。 There are other, better , options. 还有其他更好的选择。 I urge you not to reach for goto
as the first tool you use. 我强烈建议您不要将goto
作为您使用的第一个工具。
You can't use goto
to move between functions, and a lambda defines a separate function to it's enclosing scope. 你不能使用goto
在函数之间移动,而lambda为它的封闭范围定义了一个单独的函数。
From this reference 从这个参考
The
goto
statement must be in the same function as the label it is referring, it may appear before or after the label.goto
语句必须与它所引用的标签具有相同的功能,它可能出现在标签之前或之后。
And the standard, [stmt.goto]
和标准, [stmt.goto]
The
goto
statement unconditionally transfers control to the statement labeled by the identifier.goto
语句无条件地将控制转移到标识符标记的语句。 The identifier shall be a label located in the current function. 标识符应该是位于当前函数中的标签。
The goto
statement transfers control to the location specified by label. goto
语句将控制权转移到label指定的位置。 The goto
statement must be in the same function as the label it is referring, it may appear before or after the label. goto
语句必须与它所引用的标签具有相同的功能,它可能出现在标签之前或之后。
You can instead do this: 你可以这样做:
#include <iostream>
int main()
{
auto lambda = []() {
goto label;
return;
label:
std::cout << "hello, world!" << std::endl;
};
lambda();
return 0;
}
And it will print "Hello World". 它将打印“Hello World”。 See demo . 见演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.