lambda value capture by reference



Create a local int. Write a lambda expression which captures the int, and decrement it until it reaches 0. Once it is 0, stop decrementing; return true once 0 is reached.

i wrote the following lambda expression and i am capturing a1 by reference.however when i check the value of a1 it is still 3 even though i have captured it by reference ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

int a1 = 3;

	auto f = [&a1]() -> bool{ 

		while (a1 > 0)
		 { 
		   --a1;
		 }

		 if (a1 == 0)
		 {
			 return true;
		 }
	};

	cout << boolalpha; 

	cout << " the lambda expression is " << f() << "value of a1 is " << a1 << endl; 

> cout << " the lambda expression is " << f() << "value of a1 is " << a1 << endl;

Prior to C++17, the evaluations of f() and a1 are unsequenced.

To get the behaviour that you expect in C++14, write it as two separate full expressions.

1
2
std::cout << "the closure returned: " << f() << '\n' ; 
std::cout << "the value of a1 is: " << a1 << '\n' ; 

Topic archived. No new replies allowed.