
Three ways to pass function parameters
1. Pass by value. When passing, the formal parameters and actual parameters each occupy an independent space.
2. Address transfer is to transfer the storage address of the actual parameter to the formal parameter.
3. Passing by reference is an alias with a reference as the actual parameter, which is the same variable as the actual parameter.
Sample code
Pass by value
#includevoid swap1(int x, int y)//定义中的x,y变量是swap函数的两个形参 { int tmp; tmp = x; x = y; y = tmp; printf("x=%d,y=%d\n", x, y); } int main() { int a = 2; int b = 3; swap1(a, b);//a,b变量为swap函数的实际参数 printf("a=%d,b=%d", a, b); return 0; }
Pass by address
void swap2(int *px, int *py) { int tmp; tmp = *px; *px = *py; *py = tmp; printf("px=%d,py=%d\n", *px, *py); } int main() { int a = 2; int b = 3; swap2(&a, &b);/*调用了swap函数,同样也有隐含动作px=&a;py=&b;*/ printf("a=%d,b=%d", a, b); return 0; }
Pass by reference
#includevoid swap3(int &x,int &y) { int tmp = x; x = y; y = tmp; printf("x=%d,y=%d\n", x, y); } int main() { int a = 2; int b = 3; swap3(a, b);//调用方式与传值一样 printf("a=%d,b=%d", a, b); system("pause"); return 0; }
Recommended tutorial :《C# tutorial》
The above is the detailed content of Three ways to pass parameters to a function. For more information, please follow other related articles on the PHP Chinese website!
What programming language is c language?
How to use the Print() function in Python
ppt insert page number
okex official website
How to solve disk parameter errors
The difference between Hongmeng system and Android system
How to enable the same city function on Douyin
Else usage in Python loop structure