Home >Backend Development >C++ >Why Do Lambda Expressions Capture the Final Value of Iteration Variables, and How Can This Be Avoided?

Why Do Lambda Expressions Capture the Final Value of Iteration Variables, and How Can This Be Avoided?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 06:09:43916browse

Why Do Lambda Expressions Capture the Final Value of Iteration Variables, and How Can This Be Avoided?

Risks of using iteration variables in Lambda expressions

Lambda expressions provide a concise way to define inline functions in loops. However, using iteration variables directly in lambdas may lead to unexpected behavior later.

Lambda trap of iterating variables:

Consider the following code:

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

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

One might think that each lambda will print the corresponding value of i. However, due to closures, all lambdas share the same captured reference to i.

Unexpected print result:

When the loop exits, i becomes 10 and all lambdas now point to this final value. As a result, executing the lambda will print "10" ten times instead of the expected sequence from 0 to 9.

This behavior results from lambda closures maintaining references to variables declared within their scope, even after the loop has completed.

Avoidances and alternatives:

To solve this problem, create a local variable in the loop and assign it the value of the iteration variable:

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

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

This ensures that each lambda captures a different value of j, resulting in the expected sequence of prints.

Keep in mind that using iteration variables directly in lambda expressions may lead to unexpected closure-related conditions. Instead, consider creating local variables to capture exactly the value you need.

The above is the detailed content of Why Do Lambda Expressions Capture the Final Value of Iteration Variables, and How Can This Be Avoided?. 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