1. 函数:C语言的最小执行单元
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
1.1 函数的基本结构
int sum(int a, int b) {
int result = a + b;
return result;
}
1.2 函数的底层实现
栈内存分配结构:
- 返回地址
- 参数值拷贝
- 局部变量存储区
- 寄存器保存区
2. 函数的参数传递:值传递的陷阱
2.1 基本类型参数传递
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
2.2 指针参数的妙用
void real_swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
2.3 数组参数的特殊处理
void print_array(int *arr, int len) {
for(int i=0; i<len; i++){
printf("%d ", arr[i]);
}
}
3. 函数的返回值:不仅仅是数据输出
3.1 返回指针的注意事项
int* dangerous_func() {
int local = 100;
return &local; // 错误示例
}
3.2 多返回值实现技巧
typedef struct {
int sum;
int product;
} Result;
Result calculate(int a, int b) {
return (Result){a+b, a*b};
}
4. 函数指针:C语言的超能力
4.1 函数指针的声明与使用
typedef int (*CompareFunc)(int, int);
void sort(int *arr, int len, CompareFunc cmp) {
// 使用cmp指针调用比较函数
}
5. 递归函数:优雅与风险并存
5.1 经典递归案例
int fibonacci(int n) {
if(n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
5.2 递归优化技巧
#define MAX_N 100
int memo[MAX_N] = {0};
int optimized_fib(int n) {
if(n <= 1) return n;
if(memo[n] != 0) return memo[n];
memo[n] = optimized_fib(n-1) + optimized_fib(n-2);
return memo[n];
}
6. 可变参数函数:灵活性的代价
#include <stdarg.h>
double average(int count, ...) {
va_list ap;
va_start(ap, count);
double sum = 0;
for(int i=0; i<count; i++){
sum += va_arg(ap, double);
}
va_end(ap);
return sum / count;
}
7. 函数的高级技巧
7.1 函数属性扩展
__attribute__((always_inline)) void fast_func() {}
7.2 动态加载函数
#include <dlfcn.h>
void* handle = dlopen("./mylib.so", RTLD_LAZY);
8. 常见函数问题排查
调试命令:
valgrind --leak-check=full ./your_program
gprof program gmon.out > analysis.txt
9. 现代C语言函数新特性
9.1 C11泛型选择
#define cbrt(X) _Generic((X), \
long double: cbrtl, \
default: cbrt, \
float: cbrtf)(X)
10. 最佳实践指南
/**
* @brief 计算加权和
* @param weight 权重系数(0.0-1.0)
*/
float weighted_sum(float a, float b, float weight) {
weight = (weight < 0.0f) ? 0.0f : (weight > 1.0f) ? 1.0f : weight;
return a * weight + b * (1 - weight);
}