C语言函数参数 #
一、形参与实参 #
1.1 概念 #
- 形参:函数定义时的参数
- 实参:函数调用时的参数
c
int add(int a, int b) {
return a + b;
}
int main() {
add(1, 2);
return 0;
}
二、值传递 #
2.1 基本概念 #
C语言默认是值传递,形参是实参的副本。
2.2 示例 #
c
#include <stdio.h>
void modify(int a) {
a = 100;
printf("函数内: %d\n", a);
}
int main() {
int x = 10;
modify(x);
printf("函数外: %d\n", x);
return 0;
}
输出:
text
函数内: 100
函数外: 10
三、指针传递 #
3.1 通过指针修改 #
c
#include <stdio.h>
void modify(int* a) {
*a = 100;
}
int main() {
int x = 10;
modify(&x);
printf("x = %d\n", x);
return 0;
}
3.2 交换两个数 #
c
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("x=%d, y=%d\n", x, y);
return 0;
}
四、数组传递 #
4.1 数组作为参数 #
c
#include <stdio.h>
int sum(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return total;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
printf("总和: %d\n", sum(arr, 5));
return 0;
}
五、const参数 #
5.1 保护参数 #
c
#include <stdio.h>
void print_string(const char* str) {
printf("%s\n", str);
}
const保证函数不会修改参数。
六、总结 #
| 传递方式 | 特点 |
|---|---|
| 值传递 | 不修改原值 |
| 指针传递 | 可修改原值 |
| 数组传递 | 传递首地址 |
下一步,让我们学习递归函数!
最后更新:2026-03-26