Home > Backend Development > C++ > Why Do Lambda Expressions in Loops Produce Unexpected Results?

Why Do Lambda Expressions in Loops Produce Unexpected Results?

Linda Hamilton
Release: 2025-01-14 11:26:46
Original
721 people have browsed it

Why Do Lambda Expressions in Loops Produce Unexpected Results?

Lambda Expressions and Loop Iteration Variables: A Potential Pitfall

Using loop iteration variables directly within lambda expressions is generally discouraged. This practice can produce unexpected outcomes due to how lambda expressions handle variable capture.

Lambda expressions capture the reference to a variable, not its value at the time of capture. Therefore, when a loop iterates, the lambda expressions created within the loop all reference the same, ever-changing iteration variable. This leads to all lambdas ultimately using the variable's final value after the loop completes, not its value at the time each lambda was created.

Let's illustrate this with a VB.NET example:

<code class="language-vb.net">Dim actions = new List(Of Action)()

For i As Integer = 0 To 9
    actions.Add(New Action(Function() Console.WriteLine(i)))
Next

For Each action As Action In actions
    action()
End For</code>
Copy after login

You might expect this to print 0 through 9. Instead, it prints 10 ten times! This is because each Action in the actions list references the same i, and by the time the second loop executes, i has already reached its final value of 10.

The problem is amplified when the loop body has side effects impacting the variable referenced by the lambda expression. This can lead to difficult-to-debug inconsistencies.

The Solution: Create a Local Copy

To prevent this, create a local copy of the iteration variable inside the loop:

<code class="language-vb.net">Dim actions = new List(Of Action)()

For i As Integer = 0 To 9
    Dim localI As Integer = i ' Create a local copy
    actions.Add(New Action(Function() Console.WriteLine(localI)))
Next

For Each action As Action In actions
    action()
End For</code>
Copy after login

Now, each lambda expression captures a unique localI variable, holding its value at the time of creation. The output will correctly be 0 through 9. This simple change ensures each lambda operates with its own independent value, avoiding unexpected behavior.

The above is the detailed content of Why Do Lambda Expressions in Loops Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template