Is there any way to use goto statement in lambda expression?
#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:
use of undeclared label 'label'
goto label;
^
1 error generated.
Is there any way to use goto statement in lambda expression?
No. Not to leave the scope of lambda and jump to the enclosing scope. You can only goto
a labeled statement inside the lambda, same as if it were any other function.
Having said that, the uses for goto
in C++ specifically are few and infrequent. There are other, better, options. I urge you not to reach for goto
as the first tool you use.
You can't use goto
to move between functions, and a lambda defines a separate function to it's enclosing scope.
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.
And the standard, [stmt.goto]
The
goto
statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label located in the current function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With