Pass by value Example

I compiled an ran this example but I can't seem to understand why it prints out a 3 and not a 2 if it should be decremented...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;

void decrement_it(int);

int main() 
{
   int y = 3;
   decrement_it(y);
   cout << "y = " << y << endl;
   return 0;
}

void decrement_it(int y) 
{
   y--;
}
When you pass y to decrement you make a copy of y. In your decrement function you decrement the copy not the original.
To add to what @Yanson said. You're sending in a copy of the variable y. Then you're making the variable y into the number 2. But the original never left, you havent touched it. You have to pass it by reference, which is when you pass in the original and it should work -

void decrement_it(int& y)
Last edited on
Ahh I get it. Thanks!
Topic archived. No new replies allowed.