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 get close to this with by using a lambda in C++. Generally, when you set a variable like
int x;
int y;
int z{x + y};
z
will only be the result of x + y
at that time. You'd have to do z = x + y;
every time you change x
or y
to keep it update.
If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like
int x;
int y;
auto z = [&](){ return x + y; };
cin >> x;
cin >> y;
cout << z();
and now z()
will have the correct value instead of the uninitialized garbage that the original code had.
If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like
auto z = [&](){ static auto cache_x = x;
static auto cache_y = y;
static auto cache_result = x + y;
if (x != cache_x || y != cache_y)
{
cache_x = x;
cache_y = y;
cache_result = x + y;
}
return cache_result;
};