Reputation: 128
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. Thanks in advance for your answers!
Upvotes: 0
Views: 1308
Reputation:
You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}
Upvotes: 0
Reputation: 122350
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;
}
Upvotes: 1
Reputation: 170064
int sum = a + b;
writes the result of adding a
and b
into the new variable sum
. It doesn't make sum
an expression that always equals the result of the addition.
Upvotes: 2
Reputation: 409166
Execution of your code is linear from top to bottom.
You modify b
after you initialize sum
. This modification doesn't automatically alter previously executed code.
Upvotes: 2