Can a lambda capturing nothing access global variables?

后端 未结 3 2002
走了就别回头了
走了就别回头了 2021-02-05 04:07
int n;    
int main()
{
    [](){ n = 0; }(); // clang says \"ok\"

    int m;
    [](){ m = 0; }(); // clang says \"not ok\"
}

I just wonder:

3条回答
  •  走了就别回头了
    2021-02-05 04:54

    Global, static and const variables are accessed by default:

    #include 
    
    int n;    
    int main()
    {
        [](){ n = 10; }();
        std::cout << n << std::endl;
        static int m = 1;
        [](){ m = 100; }();
        std::cout << m << std::endl;
        const int l = 200;
        [](){ std::cout << l << std::endl; }();
    }
    

提交回复
热议问题