Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Call by reference

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?

like image 808
user3828158 Avatar asked Sep 25 '26 02:09

user3828158


1 Answers

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.

like image 124
mathematician1975 Avatar answered Sep 27 '26 15:09

mathematician1975



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!