Pass by reference (&)

Can someone explain/give me an example of how the & symbol is used in C++. I looked at a couple of tutorials and read up on it but still dont understand. Thanks!

Lets say you have these two variables, pass-by-value and pass-by-reference:

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

void passByValue(int variable){
    // Increment variable
    variable++;    
    cout << variable << endl;
}

void passByReference(int &variable){
    // Increment variable
    variable++; 
    cout << variable << endl;
}

int main(){
    
    int byValue = 0;
    int byReference = 0;
    
    // Increment the variables by 1
    passByValue(byValue);
    passByReference(byReference);
    
    cout << "byValue after incrementing is: " << byValue << " and byReference after incrementing is: " << byReference;
}

This gif helped me understand the difference when I first learned pass-by-value vs pass-by-reference
https://blog.penjee.com/wp-content/uploads/2015/02/pass-by-reference-vs-pass-by-value-animation.gif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void modifyMe(int &value) {
    value = 42;
}

void modifyMe2(int value) {
    value = 9001;
}

auto main() -> int {
    int myInt = 10;
    std::cout << myInt << std::endl; // 10
    
    modifyMe(myInt);
    std::cout << myInt << std::endl;  // 42

    modifyMe2(myInt);
    std::cout << myInt << std::endl; // 42
}


Pass-by-reference allows one to modify the value of what was passed to the function.

Your confusion may arise from the fact that the & symbol is also used in other contexts apart from pass-by-reference.

It is used as an address-of operator when we do:

1
2
int myInt = 42;
int *ptr = &myInt;


This makes ptr point to the address of the variable myInt.

When we do lambda expressions to capture references to variables within the current scope:

1
2
3
4
5
6
7
8
9
10
{
    int myInt = 42;
    int *ptr = &myInt;
    auto myFunc = [&]() -> void {
        *ptr = 9001;
        std::cout << myInt << std::endl;
    };

    myFunc(); // 9001
}


These are the only uses I've found, but there might be others. All you need to do is to pay attention to how it's being used to know what behaviour to expect.
Topic archived. No new replies allowed.