Home > Backend Development > C++ > body text

Parameter passing technology in C/C++

WBOY
Release: 2023-08-31 13:41:06
forward
811 people have browsed it

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";
}
Copy after login

Output

(a,b) = (10, 40)
(a,b) = (10, 40)
Copy after login

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";
}
Copy after login

Output

(a,b) = (10, 40)
(a,b) = (40, 10)
Copy after login
Copy after login

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";
}
Copy after login

Output

(a,b) = (10, 40)
(a,b) = (40, 10)
Copy after login
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template