According to the C++11 standard, lambda expressions may use variables in the enclosing scope, by means of the capture list, the parameter list or both.
So, let's look to two versions of the same code.
1) With capture
int x = 4;
cout << "With capture : Factorial of " << x << " = " << [x]() // <= Capture
{
int r = 1;
for (int i = x; i > 1; i--) r = r * i;
return r;
}() << endl;
2) With parameter
int x = 4;
cout << "With parameter: Factorial of " << x << " = " << [](int x) // <= Parameter
{
int r = 1;
for (int i = x; i > 1; i--) r = r * i;
return r;
}(x) << endl;
The output is:
With capture : Factorial of 4 = 24
With parameter: Factorial of 4 = 24
Since we can pass parameters to lambdas in the parameter list (just as with any C++ function), why do we need the capture list?
Can someone show me cases where parameter list doesn't work and only capture list does?