It’s been a long time since I wrote a blog. I’m just lazy. I’ve
said that whether it’s technology or knowledge, what matters is output rather than input. Only the knowledge you can use is yours. Blogging is a good testing process. Being able to explain what you have learned in
an easy-to-understand manner can both teach others and improve yourself quickly.
Recently, I reviewed some basic knowledge of the C language and summarized some simple knowledge points. The basics are really important...
At the same time, I also set a flag for myself, study hard, summarize more, write more blogs...
When calling a function, there are two ways to pass parameters to the function:
Call by value
This method copies the actual value of the parameter to the formal parameter of the function. In this case, modifying the formal parameters in the function will not affect the actual parameters.
#include <stdio.h>
/* 函数声明 */
void swap(int x, int y);
int main ()
{
/* 局部变量定义 */
int a = 100;
int b = 200;
printf("交换前,a 的值: %d\n", a );
printf("交换前,b 的值: %d\n", b );
/* 调用函数来交换值 */
swap(a, b);
printf("交换后,a 的值: %d\n", a );
printf("交换后,b 的值: %d\n", b );
return 0;
}
/* 函数定义 */
void swap(int x, int y)
{
int temp;
temp = x; /* 保存 x 的值 */
x = y; /* 把 y 赋值给 x */
y = temp; /* 把 temp 赋值给 y */
return;
}
Output result
Before the exchange, the value of a: 100
Before the exchange, the value of b: 200
After the exchange, the value of a: 100
After the exchange, the value of b: 200
It can be seen from the result that only the values of a and b are exchanged within the function, but the values of a and b are not actually changed.
Call by reference
Through the pointer transfer method, the formal parameter is a pointer to the address of the actual parameter. When the pointer is operated on the formal parameter, it is equivalent to the operation on the actual parameter itself.
#include <stdio.h>
/* 函数声明 */
void swap(int *x, int *y);
int main ()
{
/* 局部变量定义 */
int a = 100;
int b = 200;
printf("交换前,a 的值: %d\n", a );
printf("交换前,b 的值: %d\n", b );
/* 调用函数来交换值
* &a 表示指向 a 的指针,即变量 a 的地址
* &b 表示指向 b 的指针,即变量 b 的地址
*/
swap(&a, &b);
printf("交换后,a 的值: %d\n", a );
printf("交换后,b 的值: %d\n", b );
return 0;
}
/* 函数定义 */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* 保存地址 x 的值 */
*x = *y; /* 把 y 赋值给 x */
*y = temp; /* 把 temp 赋值给 y */
return;
}
Output result
Before the exchange, the value of a: 100
Before the exchange, the value of b: 200
After the exchange, the value of a: 200
After the exchange, the value of b: 100
It can be seen from the output result that, unlike the call by value, the formal parameter in the function is a pointer to the address of the actual parameter, and the pointing operation on the formal parameter is also equivalent to the operation on the actual parameter itself.
Reference materials: rookie tutorials, etc.
Welcome to pay attention, learn and improve together! ! !