Function Parameter Passing MethodsIn C language, the methods of passing function parameters can be roughly divided into two types: one is pass by value, and the other is pass by address.Pass by ValuePass by value, as the name suggests, means passing the value of the actual parameter, and it is a copy of the value. In this method, the value of the actual parameter generally will not be modified after the function’s execution. For example, in the following sample code, the value of the actual parameter y is not modified and remains 1.
#include <stdio.h>// b is the formal parameter
void add1(int b) {
b++;
}
int main() {
// y is the actual parameter
int y = 1;
add1(y);
printf("y's value has not been modified, it is: %d\n", y);
return 0;
}
This is why (Principle)I believe this is because, after the function add1() is called, it is the local variable b that is incremented by 1 and reassigned to b, not the actual parameter y. The local variable b is only defined and initialized with the value of variable y when the function is called, and it is just a copy of y’s value. After that, y does not participate in the function’s execution process, so y’s value will not be modified.Pass by AddressThe other way to pass parameters in C language functions is by address, which means passing the memory address of the variable to the function. For example, in the following code, the value of xyz will be modified:
#include <stdio.h>
void add2(int *c) {
*c = *c + 1;
}
int main() {
int xyz = 2;
add2(&xyz);
printf("xyz's value has been modified, it is %d\n", xyz);
return 0;
}
The code compiles and runs, producing the output:
xyz's value has been modified, it is 3
This is why (I believe) by declaring the function’s formal parameter as a pointer type, the memory address pointed to by the actual parameter is passed to the function during the function call. Thus, the value received by the function’s formal parameter is the memory address of the variable. In this way, although the function still operates on its own local variable (the formal parameter), it is not the actual parameter, but it changes the value at the memory address, thereby modifying the value of any variable pointing to that memory address. For example, modifying the value of a double pointer pointing to a pointer will also change the value of the single pointer, as shown in the following sample code:
#include <stdio.h>
int main() {
int a = 1;
int *p = &a;
int **p2 = &p;
**p2 = 2;
printf("The value pointed to by pointer p has been modified to: %d\n", *p);
printf("The value of variable a has also been modified to: %d\n", a);
return 0;
}
The above code compiles and runs, producing the output:
The value pointed to by pointer p has been modified to: 2
The value of variable a has also been modified to: 2
Disclaimer: The content is for reference only, and does not guarantee correctness. It should not be used as the basis for any decisions!