1. Call-to-value mechanism (Call-by-value machanism)
(1). The value of the argument is inserted at the formal parameter position. If the argument is a variable, only the value of the variable is inserted, not the variable itself.
(2). The value call parameter is a local variable. When the function is called, the parameter of the function is initialized to the value of the argument.
eg
void swap (int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
Main ()
{
int a = 1, b = 2;
cout << "a =" << a << "b=" << b << "\ n";
Swap (A, b);
return 1;
}
Operation Result:
A = 1 B = 2
A = 1 B = 2
Description: No occurrence worth exchanging
2. Invoking a referral mechanism
(1). Replace the parameter with the memory location of the argument. Because program variables are implemented as memory locations, these memory locations are variables. That is, the variable itself is inserted at the formal parameter position, not the value of the variable.
(2). The reference call parameter is replaced by the memory location of the argument, so the variable will change if the memory location is modified in the function body.
eg
eg
void swap (int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
The result that appears:
A = 1 B = 2
A = 2 B = 1
For the above two examples explained in detail:
In the first example, when the swap function is called, the values of A and B are passed to X and Y, where x and y are relative to the copy of A and B, and the change of the copy does not change the value of the variable itself.
In the second example, the SWAP function defines a reference to X, Y, when the main function calls swap, x and Y are references to A and b respectively, at which point X and a represent the same variable, y and b represent the same variable, and when x and Y are exchanged, A and B are exchanged, which makes two variables worth exchanging.
C + + arguments and parameters Exchange variable values