Daily C++ Puzzle 1

The loop variable every lambda shares

A short C++ program with a bug: the loop variable every lambda shares. The answer, the observed output, the fix, and the lesson are on this page.

#include <functional>
#include <iostream>
#include <vector>

int main() {
    std::vector<std::function<void()>> fns;
    int i; // declared OUTSIDE the loop: still alive when the lambdas run
    for (i = 0; i < 3; ++i) {
        fns.push_back([&] { std::cout << i << ' '; });
    }
    // i is 3 by now, and every lambda captured the SAME i by reference.
    for (auto& f : fns) f();
    std::cout << '\n';
}

Every lambda captured i by reference, and there is only one i. By the time the lambdas run, the loop has finished and i is 3 — so all three print 3.

Observed output: 3 3 3.

Fix: capture by value ([i]) or capture a copy ([i = i]).

Lesson: a reference capture shares the variable, it does not snapshot it.

Harder cousin (observed, not shipped as the puzzle): when i is declared inside the for header, the lambdas outlive it — a dangling reference, and the output is outright garbage that changes run to run. Observed once on the box: 1840247600 1840247632 1840247664. That is undefined behavior, not a wrong number: the lesson is that the classic form is a logic bug and the for-header form is worse.

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.