Referencing local variable before assignment results in unexpected behavior

Indeed! that’s one of the few things I liked when programming in C++…

Here’s a simple example for people unfamiliar with C++:

#include <iostream>
#include <functional>

void call_f(std::function<void()> f) {
    // Just call f
    f();
}

int main() {
    int x = 5;

    // This lambda can read `x`
    call_f([x]{ std::cout << x+10 << "\n"; });

    // This lambda can change `x`
    call_f([&x]{ x = 4; });

    std::cout << "x: " << x << "\n";

    return 0;
}

// Test:
$ g++ a.cc && ./a.out
15
x: 4

It makes it clear which variable might be modified by the lambda.

We can also write[&]{ ... } to capture all necessary variables by reference (approximately equivalent to the Julia behavior), and [=]{ ... } to capture them by copy.