The method of changing the variable value in the main function by the sub-function in C language

When learning C language today, I found that when I want to change the value of the variable in the main function in the sub-function, I can't change the value of the variable in the main function by using it directly. For example, the following example swaps the values ​​of two variables:

 

#include"stdio.h"

// 函数返回类型的地方写出:void,表示这个函数不返回任何值,也不需要返回;
void Swap(int a, int b) {
	int z = 0;
	z = a;
	a = b;
	b = z;
}

int main() {
	int a = 10;
	int b = 20;

	// 写一个函数交换两个整型变量的值;

	printf("交换前:a=%d  b=%d\n", a, b);
	Swap(a, b);
	printf("交换后:a=%d  b=%d\n", a, b);
	return 0;
}

 After the above program is run, it is found that the results before and after the exchange are the same, and the value is also exchanged in the sub-function, but not in the main function. I think the reason is that in the sub-function The variables are all temporary variables, which will be destroyed after the function is called, and will not affect the variables in the main function. At this time, if you want to change the variable in the main function, you need to use the address of the variable. Changing the value in the address is the most direct and effective way. See the following program, after the change:

 

#include"stdio.h"

// 函数返回类型的地方写出:void,表示这个函数不返回任何值,也不需要返回;
void Swap(int *a, int *b) {
	int z = 0;
	z = *a;
	*a = *b;
	*b = z;
}

int main() {
	int a = 10;
	int b = 20;

	// 写一个函数交换两个整型变量的值;

	printf("交换前:a=%d  b=%d\n", a, b);
	Swap(&a, &b);
	printf("交换后:a=%d  b=%d\n", a, b);
	return 0;
}

In this way, the effect of exchanging variable values ​​can be obtained by running the program, that is, the value of the variable in the main function is changed in the sub-function. The most effective and direct method is to pass in the address of the variable and change the value in the address.

Guess you like

Origin blog.csdn.net/xingyuncao520025/article/details/130777284