Skip to content

Function call argumens (1)

Course: C++ Part 2 - chapter 4

int f(int x, int y) {
x = 10;
y = 20;
}
int a = 30;
int b = 40;
f(a, b);
cout<<a<<" "<< b; // Prints 30 40

The above code is an example of call by value approach. Here, 2 new variables x and y gets created. So when we change the value of x and y, it does not affect a and b.

💡 Whenever you use call by value, new variable is created. So be mindful of this especially during recursions.

int f(int &x, int &y) {
x = 10;
y = 20;
}
int a = 30, b = 40;
f(a, b);
cout<<a<<" "<<b; // Prints 10 20

The above code is an example of call by reference approach. As mentioned before, & means creating a reference which is an alias / alternate name for the variable. Here x and y just becomes alternate names for the variables a and b respectively. They don’t have any memory allocation of their own. So setting x = 10 is equivalent to writing a = 10.

int f(int *x, int *y) {
*x = 10;
*y = 20;
}
int a = 30, b = 40;
f(&a, &b);
cout<<a<<" "<<b; // Prints 10 20

Here, we are passing address of a and b. So x holds address of a and y holds address of b.

Now we are directly making the change in the address, so value of a and b are updated.