Wait, why did all functions return 2?
The lambdas donβt capture the value of
This is called late binding and can cause unexpected behavior when creating closures inside loops.
So as a quick tip, Bind the current value at definition time using a default argument(like shown in the second image) Then each lambda remembers its own
The lambdas donβt capture the value of
i
at each loop iteration, they capture the variable itself. By the time you call the functions, the loop has finished, and i
is left at its final value, 2.This is called late binding and can cause unexpected behavior when creating closures inside loops.
So as a quick tip, Bind the current value at definition time using a default argument(like shown in the second image) Then each lambda remembers its own
i
value independently.β€2