How to use goto statement in lambda expression C++

  • A+
Category:Languages

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. 

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: