Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error when combining lambda captures

Tags:

c++

c++11

Someone asked me why this code does not compile:

int main()
{
    int a = 0;
    int x = 3, y = 2, z = 1;
    auto f = [&a,=]() { a = x + y + z; };
    f();
}

I've checked in Visual Studio 2017 and with wandbox for gcc HEAD 8.0.0 201708 and it's true, it doesn't compile.

The first gcc error is just:

error: expected identifier before '=' token

on the line with the lambda, and it's complaining about the = in the capture clause.

What's wrong with the code?

like image 649
Kate Gregory Avatar asked Aug 06 '17 19:08

Kate Gregory


1 Answers

For a lambda, default capture must be first.

auto f = [=, &a]() { a = x + y + z; };

Live Demo

like image 197
AndyG Avatar answered Sep 28 '22 03:09

AndyG