c language-function parameter transfer

Procedure 1: Value passing

#include<iostream>
#include<cstdio>

using namespace std;

void Exchg1(int x, int y)
{
	int tmp;
	tmp = x;
	x = y;
	y = tmp;
	printf("x = %d, y = %d\n",x, y);
}

int main()
{
	int a = 4, b = 6;
	Exchg1(a, b);
	printf("a = %d, b = %d\n", a, b);
	return 0;
} 

It was exchanged in Exchg1, but it did not work in the main function.

Reason: When the function is called, it implicitly assigns the values ​​of the actual parameters a and b to x and y, and then no more operations are performed on a and b in the written function body. The exchange is just x, y variables. Not a, b. Of course, the values ​​of a and b have not changed. The function just passes the values ​​of a and b to x and y through the paid value. The operation in the function is just that the values ​​of x and y are not the values ​​of a and b. This is called value passing.

Procedure 2: Address transfer

#include<iostream>
#include<cstdio>

using namespace std;

void Exchg1(int *x, int *y)
{
	int tmp;
	tmp = *x;
	*x = *y;
	*y = tmp;
	printf("x = %d, y = %d\n",*x, *y);
}

int main()
{
	int a = 4, b = 6;
	Exchg1(&a, &b);
	printf("a = %d, b = %d\n", a, b);
	return 0;
} 

To achieve digital swap.

The implicit copy operation of the function is to give the addresses of a and b to x and y. It can be seen that the values ​​of the pointers x and y are the address values ​​of the a and b variables, respectively. Next, the operation on * x, * y is of course the operation on the a and b variables themselves.

Procedure 3: Pass by reference

#include<iostream>
#include<cstdio>

using namespace std;

void Exchg1(int &x, int &y)
{
	int tmp;
	tmp = x;
	x = y;
	y = tmp;
	printf("x = %d, y = %d\n",x, y);
}

int main()
{
	int a = 4, b = 6;
	Exchg1(a, b);
	printf("a = %d, b = %d\n", a, b);
	return 0;
} 

To achieve digital swap.

x and y refer to a and b variables respectively. In this way, the actual operation of the function is the actual parameters a, b itself. In other words, the function can be directly modified to the value of a, b.

The difference between value passing and reference passing:

1: Different in function definition format.

2: The same format when called.

3: The function is different. (One operation is not the variable itself, one is itself)

Published 158 original articles · Like 10 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/ab1605014317/article/details/105590456