Problem of scope of variables

Hi, I'm testing on a super simple code.
However, I can't understand why isn't the output as expected.
Below is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

void double_value(int);

int main()
{
   int a = 10;

   double_value(a);
   cout << a;

   return 0;
}

void double_value(int b)
{
   b = b*2;
}


The output result is 10, instead of 20. Why isn't the double_value function in main working? I'm guessing it's the problem of scope of variable.
Thx in advance!
By default, variables are passed by value. This means a copy of the variable is passed into a function.

Modifying this copy does not change the original variable in main.

To let double_value modify the value of the original variable, it needs to be passed by reference.

1
2
3
4
5
6
7
8
void double_value(int&);

// ...

void double_value(int& b)
{
    b = b*2;
}
Last edited on
Right, got it!
Thanks a lot:)
Topic archived. No new replies allowed.