Home >Backend Development >C++ >Why Does Using Iteration Variables in Lambda Expressions Lead to Unexpected Results?

Why Does Using Iteration Variables in Lambda Expressions Lead to Unexpected Results?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 07:51:50488browse

Why Does Using Iteration Variables in Lambda Expressions Lead to Unexpected Results?

Understanding the Unexpected Behavior of Iteration Variables in Lambda Expressions

A developer recently encountered a compiler warning regarding the use of loop iteration variables inside lambda expressions. This highlights a common pitfall leading to unexpected program behavior. Let's explore why this occurs.

Consider this code example:

<code class="language-csharp">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>

One might expect this to print numbers 0 through 9 sequentially. Instead, it prints "10" ten times. This is because the lambda expressions don't capture a copy of i for each iteration. Instead, they capture a reference to the variable i. By the time the foreach loop executes, the loop has completed, and i holds its final value of 10. Each lambda expression, therefore, prints this final value.

This unexpected outcome underscores the importance of avoiding this coding pattern. The compiler warning serves as a crucial safeguard. To achieve the desired sequential output, create a new variable inside the loop and assign the iteration variable's value to it:

<code class="language-csharp">List<Action> actions = new List<Action>();

for (int i = 0; i < 10; i++)
{
    int j = i; // Capture a copy of i
    actions.Add(() => Console.WriteLine(j));
}

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

This revised code correctly prints 0 to 9 because each lambda expression now captures a unique, independent copy of the value j. This simple change ensures the expected and consistent behavior.

The above is the detailed content of Why Does Using Iteration Variables in Lambda Expressions Lead to Unexpected Results?. 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