Parameter Passing Techniques in C/C++

In C we can pass parameters in two different ways. These are call by value, and call by address, In C++, we can get another technique. This is called Call by reference. Let us see the effect of these, and how they work.

First we will see call by value. In this technique, the parameters are copied to the function arguments. So if some modifications are done, that will update the copied value, not the actual value.

Example

#include <iostream>
using namespace std;
void my_swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
}
int main() {
int a, b;
a = 10;
b = 40;
cout << "(a,b) = (" << a << ", " << b << ")\n";
my_swap(a, b);
cout << "(a,b) = (" << a << ", " << b << ")\n";
}

Output

(a,b) = (10, 40)
(a,b) = (10, 40)

The call by address works by passing the address of the variables into the function. So when the function updates on the value pointed by that address, the actual value will be updated automatically.

Example

#include <iostream>
using namespace std;
void my_swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a, b;
a = 10;
b = 40;
cout << "(a,b) = (" << a << ", " << b << ")\n";
my_swap(&a, &b);
cout << "(a,b) = (" << a << ", " << b << ")\n";
}

Output

(a,b) = (10, 40)
(a,b) = (40, 10)

Like the call by address, here we are using the call by reference. This is C++ only feature. We have to pass the reference variable of the argument, so for updating it, the actual value will be updated. Only at the function definition, we have to put & before variable name.

Example

#include <iostream>
using namespace std;
void my_swap(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;
}
int main() {
int a, b;
a = 10;
b = 40;
cout << "(a,b) = (" << a << ", " << b << ")\n";
my_swap(a, b);
cout << "(a,b) = (" << a << ", " << b << ")\n";
}

Output

(a,b) = (10, 40)
(a,b) = (40, 10)
Published on 03-May-2019 07:32:28