12 Aug

C++: Call-By-Value vs. Call-By-Reference

There are different ways of passing parameters to a method. It is important to know the difference between the two common ways call-by-value (CBV) and call-by-reference (CBR) to prevent confusing situations.

The two concepts will be explained using C++. For this article, I assume that you are familiar to the concept of pointers in C++.

Call-By-Value

In Call-By-Value, the data passed to a method will be copied. That is, the value held in the variable that is passed as an argument is copied into the parameters that are defined in the method header.

There is no association between the data at the caller side and the data received at the method.

Changes made to the variable within the method therefore have no effect on the variable that was passed!

As you can imagine, if you pass large data objects to a method, a call is very expensive refering performance.

Also, you need additional memory space (data is available at least twice in the memory space).

Let’s take a look at the following code listing, which shows an example of a call by value method call:

#include 


void callByValue(int x) {

    printf("Inside call_by_value x = %d before adding 10.\n", x);

    x += 10;

    printf("Inside call_by_value x = %d after adding 10.\n", x);

}


int main() {

    int a=10;

  

    printf("a = %d before function callByValue.\n", a);

    callByValue(a);

    printf("a = %d after function callByValue.\n", a);

    return 0;

}

OUTPUT:

a = 10 before function callByValue.

Inside callByValue x = 10 before adding 10.

Inside callByValue x = 20 after adding 10.

a = 10 after function callByValue.

As you can see, changing the value inside of the callByValue() method has no effect on the variable “a” which is passed to the method. The variable “a” is copied to the method’s variable “x”. At this time, we have two int valuesin our memory, both with the value 10. In the method we add 10 to the variable “x” but this does not change the value of the variable “a”. This is a typical example of a Call-By-Value method.

Call-By-Reference

Instead of copying data, you can pass references on that data. In C++ this can be done with pointers, for example.

At the caller’s side a variable points to a specific data field. At the method another pointer points to the same data. This means, that you are working on the same data inside and outside of the method. In other words, instead of copying theactual data, a pointer to the data is copied.

Let’s take a look at the following code example:

#include 


void callByReference(int *y) {

    printf("Inside callByReference y = %d before adding 10.\n", *y);

    (*y) += 10;

    printf("Inside callByReference y = %d after adding 10.\n", *y);

}


int main() {

    int b=10;

  

    printf("b = %d before function callByReference.\n", b);

    callByReference(&b);

    printf("b = %d after function callByReference.\n", b);

  

    return 0;

}

OUTPUT:

b = 10 before function callByReference.

Inside callByReference y = 10 before adding 10.

Inside callByReference y = 20 after adding 10.

b = 20 after function callByReference.

The code example is similar to the above but this time we are using pointers. The integer “b” holds thevalue 10. The method callByReference is called and the address of the variable “b” is passed to it this time.

So, when we add 10, we add 10 to the value at the memory pointed by “y”. As “y” points to the same memory as “b” we change the value of the memory “y” and “b” are pointing to. Therefore at the end of the methodthe value is 20.

Difference between pointer and reference

In C++ you can achieve a CBR with pointer or reference. So, For completeness, the difference shall be pointed out here. Pointers and references are variables that hold memory addresses as their values. They hold the addresses in memory of where you find the data of the various data types that you have

declared and assigned. Here are some differences ( you can find more differences in more detail on the websites listed in the Resources section):

A pointer can be re-assigned, a reference cannot and must be assigned at initialization example:

            //pointer
            int x = 5;
            int y = 6;
            int *p; //not initialized yet
            p = &x;
            p = &y;    //re-assigned
            *p = 10;
          
            //reference
            int &r = x;   

Pointers can point nowhere (NULL), whereas references always refer to an objects
References do not need the dereferencing operator to access the value. They can be used like “normal variables”
You can have pointers to pointers to achieve extra levels of indirection. Whereas references only offer one level of indirection
example: you can do this with pointers:

            int x = 0;
            int y = 0;
            int *p = &x;
            int *p2 = &y;
            int **pp = &p;
            pp = &p2 //*pp = p2
            **pp = 4;
            assert(y == 4);
            assert(x == 0);

Resources:

http://blog.gungfu.de/archives/2005/07/05/der-unterschied-zwischen-call-by-value-und-call-by-reference/comment-page-1/

http://abraham.informatik.fh-lausitz.de/profs/robel/faq/callByReference.html

http://www.spieleprogrammierer.de/10-faq-h%C3%A4ufig-gestellte-fragen/2309-was-ist-der-unterschied-zwischen-pointer-und-referenzen/?s=822d9b3e76e44039821ff1567d90c025ca7a2714

http://www.codingunit.com/c-tutorial-call-by-value-or-call-by-reference

http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in

http://www.geeksforgeeks.org/references-in-c/

http://www.oopweb.com/CPP/Documents/ThinkCScpp/Volume/chap16.htm

http://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf

Leave a Reply

Your email address will not be published. Required fields are marked *


− 5 = four

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">