int n;
int main()
{
[](){ n = 0; }(); // clang says "ok"
int m;
[](){ m = 0; }(); // clang says "not ok"
}
I just wonder:
If the lambda captures nothing, is it allowed to access global variables as per the C++ standard?
int n;
int main()
{
[](){ n = 0; }(); // clang says "ok"
int m;
[](){ m = 0; }(); // clang says "not ok"
}
I just wonder:
If the lambda captures nothing, is it allowed to access global variables as per the C++ standard?
Global, static and const variables are accessed by default:
Yes, sure. Normal name lookup rules apply.
Re: why local variables are treated differently from global ones.
In your example,
m
is a variable with automatic storage duration from the lambda's reaching scope, and so shall be captured.n
is not, and so doesn't have to be.Actually the
[](){ n = 10; }();
doesn't capture anything, it uses the global variable instead.See capture-list in Explaination