c++ - 如何在 lambda 表达式 C++ 中使用 goto 语句

标签 c++

有什么方法可以在lambda 表达式中使用goto 语句吗?

#include <iostream>

int main()
{
    auto lambda = []() {
        goto label;
        return;
    };
    lambda();
    return 0;
label:
    std::cout << "hello, world!" << std::endl;
}

我想让控制台输出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 lambda 中的标记语句,就好像它是任何其他函数一样。

话虽如此,goto 在 C++ 中的使用特别少且不频繁。还有其他更好的选择。我强烈建议您不要将 goto 作为您使用的第一个工具。

关于c++ - 如何在 lambda 表达式 C++ 中使用 goto 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53815203/

相关文章:

c++ - 为什么 static_cast 需要指针或引用?

c++ - VS2008下Protocol Buffer错误C2059

c++ - 为什么字符串对象需要 #include <string> 而不是字符串文字?

c++ - 项目的 QTreeWidget

c++ - 取消定义已经包含的标题

c++ - 如何在自定义 DirectShow 过滤器中以秒为单位获得正确的帧时间?

c++ - 学习 C++ : polymorphism and slicing

N 维 vector 的 C++ 模板化别名

放置在容器中时的 C++ 子类型退化

c++ - 需要推导参数*之前*用户参数的模板参数