摸鱼卷C~事半功倍? day02

28 阅读1分钟

C语言高级特性教程

1. 预处理器指令

1.1 宏定义

#define PI 3.14159265359
#define MAX(a, b) ((a) > (b) ? (a) : (b))

1.2 条件编译

#ifdef DEBUG
    #define LOG(msg) printf("DEBUG: %s\n", msg)
#else
    #define LOG(msg)
#endif

2. 位操作

2.1 基本位操作符

unsigned int flags = 0;
flags |= (1 << 0);  // 设置位
flags &= ~(1 << 0); // 清除位
if (flags & (1 << 1)) { /* 检查位 */ }

2.2 位字段

struct FilePermissions {
    unsigned int read : 1;
    unsigned int write : 1;
    unsigned int execute : 1;
};

3. 联合体(Union)

union Data {
    int i;
    float f;
    char str[20];
};

4. 可变参数函数

#include <stdarg.h>

int sum(int count, ...) {
    va_list args;
    va_start(args, count);
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += va_arg(args, int);
    }
    va_end(args);
    return total;
}

5. 函数指针高级用法

typedef void (*callback_func)(int);

void process_array(int arr[], int size, callback_func callback) {
    for (int i = 0; i < size; i++) {
        callback(arr[i]);
    }
}

6. 内联函数

static inline int max(int a, int b) {
    return a > b ? a : b;
}

7. 复合字面量

int* ptr = (int[]){1, 2, 3, 4, 5};
struct Point* center = &(struct Point){10, 20};