Call by reference & Call by value

Somebody please explain the use of call by reference and call by value.

2 Likes

Calling by value means, you just pass the values of variables to function.

void func(int A, int B)
{
    //these A and B are different variable
    //but have values same as a and b have in main
    A=100; B=500;
}
int main()
{
     int a=10, b=5;
     func(a,b);
     // a and b does not change
     cout<<a<<endl; cout<<b<<endl;
     return 0;
}

It is useful when we only need to get the value of some variable in our function. It is like passing a photocopy of variable to function for use. It is kind of safe, as, if the function tries to modify the value, only the photocopy changes, original copy remains same.

However if we actually need to modify the original value, we have to somehow pass the original variable, i.e. operations are to be performed on original variable. This can be done by passing the address of original variable. And store this address using pointers in the function. Now you can modify the original values.

void func(int* A, int* B)
{
    // A and B are pointers to a and b in main
    // so, this will change the values of a and b
    *A=100; *A=500;
    //this is changing value at the address of a and b
}
int main()
{
     int a=10, b=5;
     func(&a,&b);
     // a and b changes
     cout<<a<<endl; cout<<b<<endl;
     return 0;
}

Suppose you saw a terrorist, and you want police to kill him. You create a wax statue of the terrorist and send it to police. Now police will shoot the statue. However the terrorist is still alive. And is in same state as it was before.
But what is you send the address of the terrorist to the police? The police will go there, and will shoot it. Hence, the original terrorist will be killed! :smiley:

First case is like sending only values to the function. Second one is like using pointers!

Second case can also be achieved by using reference variables in C++. As we know, pointers are like sending address of the terrorist to the police, reference variables in C++ are like sending the terrorist himself to the police station. Terrorist will get killed in this case as well.

You can read about function call using reference variables here: link text and function call using pointer here: link text

1 Like