C++ Call by reference

user3828158 picture user3828158 · May 6, 2015 · Viewed 10k times · Source

If I have a function which takes a pointer to an integer, and I pass a reference to an integer variable from my main, is this call by value or call by reference? Sample code:

#include <iostream>

using namespace std;

void fun(int *a){
//Code block
}

int main(){
    int a = 5;
    fun(&a);
    return 0;
}

In the above code, is the call to function fun a call by value or call by reference?

Answer

mathematician1975 picture mathematician1975 · May 6, 2015

Your call is a pass by value, but of type int* not of argument type int. This means that a copy of the pointer is made and passed to the function. You can change the value of what it points to but not of the pointer.

So if your function is like this

void fun(int *a)
{
   *a = 10;
}

and you call from main like this

int main() {
    int b = 1;
    fun(&b);
    // now b = 10;
    return 0;
}

you could modify the value of b by passing a pointer to it to your function.

The same effect would be if you did the following - which is passing by reference

void fun2(int& a) 
{
    a = 5;
}

int main()
{
    int b = 10;
    fun2(b); 

    // now b = 5;
    return 0;
}

Now consider a third function that takes an integer argument by value

void fun3(int a)
{
    a = 10;
}

int main()
{
    int b = 1;
    fun3(b);
    // b  is still 1 now!
    return 0;   
}

With pass by value, fun3 changes the copy of the argument passed to it, not the variable b in the scope of main.

Passing by (non-const) reference or pointer allows the modification of the argument that is passed to it. Passing by value or const reference will not allow the argument passed to it to be changed.