Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.