Compilation error when combining lambda captures

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 checked in Visual Studio 2017 and wandbox for gcc HEAD 8.0.0 201708 and it is true, it does not compile.

First gcc error:

 error: expected identifier before '=' token 

in line with lambda and it complains about = in the capture clause.

What is wrong with the code?

+7
c ++ c ++ 11
source share
2 answers

For lambda, the default capture should be the first.

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

Live demo

+14
source share

Just to complement Andy answer, here is the standard link:

[expr.prim.lambda / 1]

 lambda-expression: lambda-introducer lambda-declarator(opt) compound-statement lambda-introducer: [ lambda-capture(opt) ] lambda-capture: capture-default capture-list capture-default , capture-list 

In particular, note that if a lambda capture contains both a default capture and a capture list, the grammar requires them to be displayed in the order above.

+5
source share

All Articles