Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use goto statement in lambda expression C++

Tags:

c++

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.
like image 511
0x11901 Avatar asked Dec 17 '18 12:12

0x11901


2 Answers

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.

like image 175
StoryTeller - Unslander Monica Avatar answered Nov 13 '22 06:11

StoryTeller - Unslander Monica


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.

like image 11
Caleth Avatar answered Nov 13 '22 06:11

Caleth