raz - 1 year ago 103
C++ Question

# Integer value assignment in c++

I'm pretty new to C++ and I have the following simple program:

`````` int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
``````

I receive always the output 15, although I've changed the value of b to 6.

There are already answers, but I feel that something is missing... When you make an assignment like

``````sum = a + b;
``````

then the values of `a` and `b` are used to calculate the sum. This is the reason why a later change of one of the values does not change the `sum`. However, since C++11 there actually is a way to make your code behave the way you expect:

``````#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
``````

This will print :

``````11
``````

This line

``````auto sum = [&](){return a + b;};
``````

declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write `sum()` then `a` and `b` are used to calculate the sum. Because `a` and `b` are captured by reference (thats the meaning of the `&`), `sum()` uses the current values of `a` and `b` and not the ones they had when you declared the lambda. So the code above is more or less equivalent to

``````int sum(int a, int b){ return a+b;}

int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download