Trouble grasping arguments passed by reference

Hello,

I can't figure out why the output of this program is 0. How does the "&" sign cause this to happen? What exactly does it mean to pass arguments by reference? I don't know why I can't grasp this. Thanks for taking the time to read.

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

void printDigitsRef(int& n) {
    while(n > 0) {
        cout << n % 10 << " ";
        n /= 10;
    }
}

int main() {
    int n;
    cout << "Enter a positive number: ";
    cin >> n;

    cout << "Digits are: ";
    printDigitsRef(n);
    cout << endl;
    cout << "The value of n is now: " << n << endl; 
    
    return 0;    
}


Output:

Enter a positive number: 1234
Digits are: 4 3 2 1
The value of n is now: 0

Have you read the tutorial on this site? It has a pretty good explanation:
http://www.cplusplus.com/doc/tutorial/functions/
Hi,

Passing by reference is handy because the value of the variable in the calling scope (main in this case) is changed. By the time printDigitsRef function is finished n is 0, the statement on line 19 reflects that.

If a variable is not passed by reference (that is by value) the function gets a local copy of that variable, the outer scope is not changed

This is a feature that allows one to change multiple values (the naive return more than 1 value scenario) by passing multiple arguments to a function, the functions parameters are declared as being references, as they are in your function.

There is more stuff about references, read about it in the tutorial and / or references material at the top left of this page.

:+)
Topic archived. No new replies allowed.