TL;DR
- Pass-by-value: value of parameters in a function will NOT be changed after function is called.
- Pass-by-reference: value of parameters in a function MIGHT be changed after function is called (when they’re updated in the function).
Pass-by-value
When you declare a variable, it allocates a memory for that variable. When you call a function foo(variable_name)
, it means you pass the value of that variable in the memory to a function. Whatever the function does, it doesn’t affect to the memory of the variable. Value of the variable remains the same.
Example code:
#include
void foo(int x);
int main() {
int a = 1;
foo(a);
printf("a: %d", a); //a: 1
return 0;
}
void foo(int x) {
x = 5;
}
In the sample code above, when you call foo(a)
:
- It actually call
foo(1)
- In the
foo(int x)
function, it allocates a new memory forx
, then setsx
to5
- In the
main
function,a
is still1
Pass-by-reference
As mentioned, when you declare a variable, it allocates a memory for that variable. Memory has memory address. When you call a function foo(variable_memory_address)
, it means you pass the memory address to a function. If you change the value of the memory in the function, you actually update the value in the memory of the variable. That’s why variable value will be changed.
Example code:
#include
void foo(int* px);
int main() {
int a = 1;
foo(&a);
printf("a: %d", a); //a: 5
return 0;
}
void foo(int* px) {
*px = 5;
}
In the sample code above, when you call foo(&a)
:
- It actually call
foo(0xAB)
(assumed memory address of variablea
is 0xAB) - In the
foo(int* px)
function, it creates a pointerpx
, andpx
points to 0xAB - When you set
*px = 5
, it means it sets the value at memory _0xAB _to5
- Then in the main function, as value in the memory of variable
a
was changed to5
, value ofa
now is5
.