This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

Argument and parameter

The actual parameter is the specific value to be assigned to the variable as the formal parameter.

A parameter cannot change an argument

Because the values used by the called function were copied from the calling function, whatever the called function does with the copied data does not affect the original data in the calling function.

Scenario 1 — First-class pointer as parameter (exchange value)

#include <stdio.h>
#include <stdlib.h>

void swqp(int *x, int *y)
{
	int tmp;
	tmp = *x;
	*x = *y;
	*y = tmp;
}

int main(int argc, char *argv[])
{
	int a = 5;
	int b = 6;

	swqp(&a, &b);

	printf("a = %d\n", a);
	printf("b = %d\n", b);

	return EXIT_SUCCESS;
}
Copy the code
liyongjun@Box20:~/project/c/study$ make t=point/point_1 run
./point/point_1.out
a = 6
b = 5
Copy the code

Scenario 2 — First-class pointer as argument (allocate space)

#include <stdio.h>
#include <stdlib.h>

void get_memory(char *x)
{
	x = (char *)malloc(1);
    printf("x = %p\n", x);
}

int main(int argc, char *argv[])
{
	char *p = NULL;

	get_memory(p);

	printf("p = %s\n", p);

	return EXIT_SUCCESS;
}
Copy the code
liyongjun@Box20:~/project/c/study$ make t=point/point_2 run
./point/point_2.out
x = 0x55d53d5942a0
p = (null)
Copy the code

Why scenario 1 is normal, but scenario 2 is wrong.

Analysis:

First of all, the calling function makes a copy of the value of the argument that it assigns to the parameter of the called function. So no change in the parameter will change the value of the argument.

In scenario 2, main() makes a copy of the value of p and assigns it to the parameter x of get_memory(). X has nothing to do with p, but main() borrows the value of p and assigns it to x as an argument. So no change in x can affect the external p. The main() function assigns NULL to the variable x, which has nothing to do with p.

Another point: although p is a pointer type, it is also a variable in itself.

In scenario 1, main() makes a copy of the address of a and assigns x to swap(). X has nothing to do with the address of a, but main() borrows the address of a and assigns x as an argument. But this is a little different from scenario 2, where &a and x both have the same value, and this value is the address of the variable a, so using this address can change the value of a, so swap() can change the value of a.

To sum up, if you pass a pointer, it is not possible to change the value of the pointer itself, it is possible to change the value of the variable to which the pointer points.

summary

Arguments are values and parameters are variables.