Home  >  Article  >  Three ways to pass parameters to a function

Three ways to pass parameters to a function

Guanhui
GuanhuiOriginal
2020-06-02 15:52:365640browse

Three ways to pass parameters to a function

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

#include
void 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

#include
void  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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn