Contact: aviboots(AT)netvision.net.il
41,500 questions
54,078 answers
573 users
#include <iostream> /* [capture](parameters) -> return_type { body }; */ // [=] - capture everything by value int main() { int x = 10; int y = 20; // A closure (anonymous function) that captures x and y by value. // [=] means "capture all used variables by value". auto add = [=]() { return x + y; }; // Use the closure int result = add(); std::cout << result << std::endl; } /* run: 30 */
#include <iostream> /* [capture](parameters) -> return_type { body }; */ // [&] - capture everything by reference int main() { int counter = 0; // Capture by reference so the lambda can modify counter auto inc = [&]() { counter++; }; inc(); inc(); std::cout << counter << std::endl; } /* run: 2 */
#include <iostream> /* [capture](parameters) -> return_type { body }; */ // Closure with parameters int main() { auto multiply = [](int a, int b) { return a * b; }; std::cout << multiply(6, 7) << std::endl; } /* run: 42 */