Home >Backend Development >C++ >Why Do Lambda Expressions Capture the Final Value of Iteration Variables?

Why Do Lambda Expressions Capture the Final Value of Iteration Variables?

Barbara Streisand
Barbara StreisandOriginal
2025-01-14 12:26:43396browse

Why Do Lambda Expressions Capture the Final Value of Iteration Variables?

Potential pitfalls of using iteration variables in Lambda expressions

In the field of programming, Lambda expressions provide a concise way to represent anonymous functions. However, using iteration variables in lambda expressions can lead to unexpected results.

Consider the following code:

<code class="language-c#">List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    actions.Add(() => Console.WriteLine(i));
}

foreach (Action action in actions)
{
    action();
}</code>

This code inadvertently associates all Lambda expressions with the same iteration variable i. Therefore, when each Lambda expression executes, it refers to the final value of i, not the expected value of i when the Lambda was created.

As a result, the output may not be as expected. Instead of printing 0 to 9 as expected, the code prints 10 ten times. It's worth noting that this behavior results from all involved delegates capturing a single variable.

To avoid this unexpected result, it is recommended to create a local variable inside the loop and assign the value of the iteration variable to it. This way, each lambda expression references a different local variable, ensuring it retains the expected value. The modified code is as follows:

<code class="language-c#">List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
    int temp = i; // 创建局部变量
    actions.Add(() => Console.WriteLine(temp));
}

foreach (Action action in actions)
{
    action();
}</code>

In this way, each Lambda expression will capture an independent temp variable, thus avoiding the problem of variable values ​​being overwritten, and the final output will correctly display 0 to 9.

The above is the detailed content of Why Do Lambda Expressions Capture the Final Value of Iteration Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn