Hang Chen
Hang Chen

Reputation: 863

Why we have to pass the values instead of the address into a "call by reference" function in C++?

I'm new to C++ and learning call by reference now.

I learned this block of code on my material:

void callByRef(&a, &b);

int main(){
    int k = 12;
    int m = 4;
    callByRef(k, m) //QUESTION HERE
    return 0;
}

void callByRef(&a, &b){
    a += 3;
    b -= 2;
    return;
}

So my question is when declaring callByRef, we use the addresses of a and b as the parameters, so when we call callByRef in the main, why we need to pass in (k, m) instead of (&k, &m)?

It's basic, but I just want to get the right picture for my future studying. Thanks guys!

Upvotes: 0

Views: 327

Answers (3)

You don't pass the value. References in C++ aren't exactly like pointers. Think of them as simply being another name for an object.

Naturally you need to bind that name to an object in order for the reference to refer to it. So for instance when we write int &i = k; we are saying that the variable that is already named k, may be referred to as i. To bind the reference, we need to name the other object. And the name of the object is k, not &k.

The same applies to function parameters and arguments. The function callByRef is specified to operate on two objects it will call a and b. When you call that function, you must name the original objects it will refer to. And the original objects are named k and m, not &k and &m.

Upvotes: 0

Artem Barger
Artem Barger

Reputation: 41232

The operator of &a means the address of variable a, the operator of *a means the content of memory addressed by variable a. Now the function definition is following:

void callByRef(int &a, int &b){
    a += 3;
    b -= 2;
    return;
}

where int &a means that a will be a reference to some variable of type int. Therefore whenever you gong to call the function you need to pass the variable itself rather its address, hence callByRef(a, b) and not callByRef(&a, &b).

The reason of such declaration is following, parameters passed to the function, passed by value, namely the content of the variable literally copied into function variable, therefore any change to it inside the function won't have any effect. For example:

void callByVal(int a, int b){
    a += 3;
    b -= 2;
    return;
}

and having:

x = 5;
y = 10;

calling callByVal(x, y) won't have any effect on x and y. To overcome this, you need to pass parameters either by reference or int &a or as an alternative you can pass pointer and update memory directly:

void callByPtr(int *a, int *b){
    *a += 3;
    *b -= 2;
    return;
}

And now it make sense to pass variables addresses, e.g. callByPtr(&a, &b).

Upvotes: 2

hahahakebab
hahahakebab

Reputation: 326

The callByRef() function passes the references as arguments so you don't need to send the explicit reference to the function. Have a read through this to understand a bit better.

Tutorial

Upvotes: 0

Related Questions