In JavaScript, we can create closure like this,
var foo = (() => { let x = 0; return () => { return x++; } })(); for (var i = 0; i < 10; i++) { var x = foo(); console.log(x); }
But translating above code into C++, it cannot work as expected for the variable, unless the variable is outside the lambda function.
// In a function int x; // variable here auto foo = [&x]() { x = 0; return [&x]() { return x++; }; }(); for (int i = 0; i < 10; i++) { int x = foo(); cout << x << endl; }
This is because C++ variable can be only accessed in the function scope. After the function return the value, the variable is not accessible anymore.
Similarly, Python can also return the function, but it cannot work as closure like JavaScript. However, Python can create non-primitive variable such as object or list so that the variable will be accessed by reference.
def _foo(): x = [0] def increment(): x[0] += 1 return x[0] return increment foo = _foo() for i in range(10): x = foo() print(x)