DEV Community

Cover image for Pass-by-value vs Pass-by-reference
Anja
Anja

Posted on • Updated on

Pass-by-value vs Pass-by-reference

Good morning! What is the difference between pass-by-value and pass-by-reference? When we have a function with parameters, we have to call it with parameters, like in the following code(language C) e.g. :

int fun(int x, int y)
{
x=1;
y=2;
}

int x=3, y=4;

fun(x,y);
printf(x=%d,y=%d, x,y);
Enter fullscreen mode Exit fullscreen mode

Lets first consider call by value. In this code the values of the parameters x and y will becopied and stored at a different memory location, meaning we have four places of memory here which store:

x=1
x=3
y=2
y=4
Enter fullscreen mode Exit fullscreen mode

When the function fun() is done, the local variables x=1 and y=2 will be deleted from memory, so when we print now x and y, it will show 3 and 4.

Lets now look at calling by reference. We also need four memory locations here, but there is an important difference:

int fun(int *p1, int *p2)
{
*p1=1;
*p2=2;
}

int x=3, y=4;

fun(&x,&y);

Enter fullscreen mode Exit fullscreen mode

Here with the “&”, we pass the memory adresses of x=3 and y=4 to the function and not the values. That means that the so called pointer parameters of the fun() function store the adress and not the values at their own memory adresses. So it would look for example like this:

p1=1000 //memory address of x
p2=2000 // memory address of y
Enter fullscreen mode Exit fullscreen mode

Inside the fun() function we write *p1, because we want to access the value of x. With *p1=1 we then change the value of x to 1 and with *p2=2 we change the value of y to 2. The * is also called the dereference operator. If you want more visuals with my explanation check out this video:
https://youtu.be/HEiPxjVR8CU
Have a nice day.😊

Discussion (0)