Home  >  Article  >  Backend Development  >  Parameter passing technology in C/C++

Parameter passing technology in C/C++

WBOY
WBOYforward
2023-08-31 13:41:06770browse

Parameter passing technology in C/C++

In C, we can pass parameters in two different ways. These are call by value and call by address, and in C we can get another technique. This is called calling by reference. Let's take a look at their effects and how they work.

First we will see call by value. In this technique, parameters are copied into function parameters. So if some modification is made, this 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)

Call by address works by passing the address of a variable into a function. So when the function updates the value pointed to by that address, the actual value is automatically updated.

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)

Same as address call, here we use reference call. This is a C-specific feature. We have to pass the reference variable of the parameter, so in order to update it, the actual value will be updated. Only in function definition we have to put & before the 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)

The above is the detailed content of Parameter passing technology in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete