0

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!

raz
  • 128
  • 1
  • 8
  • Thats how it should be. You are using two values to calculate sum. So the values of a and b are used in their current state (5 and 10). It does not have any impact on sum if you change the value of b afterwards. – Stefan Moosbrugger Nov 16 '16 at 09:59
  • 1
    Since you mention you're new to C++, you might be interested in our [list of good C++ books](http://stackoverflow.com/q/388242/1782465). – Angew is no longer proud of SO Nov 16 '16 at 10:10

4 Answers4

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

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;
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

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;
   }