Concept of C language participation in real parameters and swap functions, swap Functions
What are the formal parameters (formal argument) and actual parameters (actual argument?
Void function (int n); // n is a form parameter.
Int main {int times = 5; function (times); // times is the actual parameter}
Void function (int n) {for (int I = 0; I <n; I ++) printf ("hello \ n ");}
A parameter namedFormat parametersIn the preceding example, the formal parameter is a variable called n.
Function call function (times) assigns the value 5 of times to n. times is calledActual ParametersThat is, the value of the variable times in main () is copied to the new variable n in function.
There is a classic example in the concept of taking shape into the real parameter passing, that is, using a function to interact the values of two variables
# Include <stdio. h> void swap (int a1, int b1); int main () {int a = 0, B = 1; swap (a, B ); printf ("a = % d, B = % d", a, B);} void swap (int a1, int b1) // invalid interaction function {int temp = a1; a1 = b1; b1 = temp ;}
It is easy for beginners to write the above Code, but it does not achieve the purpose of exchange, because only the values of the formal parameters in the function are exchanged here, the real parameter only copies its value to the formal parameter. After the function is completed, the parameters in the function are also destroyed. For example, if you want to exchange the values of a and B in main, copy their values to a1 and b1 respectively in the swap function, and then the values of a1 and b1 in the function are indeed exchanged, but they are destroyed, a in main, the value of B is still the original value.
To exchange the values of a and B, it is actually equivalent to changing the value of the variable in the function. To do this, you need to pass the actual parameter address to the formal parameter, in this way, the address of the variable is copied to the variable in the function. They point to the same place in the memory and change the value of this place in the function, the value of the external variable is changed.
The following code can achieve the purpose of exchange
# Include <stdio. h> void swap (int * a1, int * b1); int main () {int a = 0, B = 1; swap (& a, & B ); // pass the real parameter address printf ("a = % d, B = % d \ n", a, B);} void swap (int * a1, int * b1) {int temp = * a1; * a1 = * b1; * b1 = temp ;}