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.
#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"; }
(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.
#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"; }
(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.
#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"; }
(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!