example3_lambda_capture_all_variables.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main() {
    int x = 10;
    int y = 20;

    auto printXY = [=]() {
        std::cout << "x = " << x << ", y = " << y << std::endl;
    };

    auto modifyXY = [&]() {
        x += 10;
        y += 10;
    };

    printXY(); // Outputs: x = 10, y = 20
    modifyXY();
    printXY(); // Still outputs: x = 10, y = 20 because the lambda captures by value

    return 0;
}
Back to lambda