In math, if z = x + y / 2
, then z
will always change whenever we replace the value of x
and y
. Can we do that in programming
You can define the following lambda z
which always returns the current value of x+y
because x
and y
are captured by reference:
DEMO
int main()
{
int x;
int y;
const auto z = [&x, &y](){ return x+y; };
std::cin >> x; // 1
std::cin >> y; // 2
std::cout << z() << std::endl; // 3
std::cin >> x; // 3
std::cin >> y; // 4
std::cout << z() << std::endl; // 7
}