C语言奇技淫巧40则
使用逗号运算符在一个语句中实现多个操作。例如:
a = 1, b = 2, c = 3;
使用条件运算符代替if语句来简化代码。例如:
x = (y > 5) ? 10 : 20;
使用位运算符来执行位操作。例如:
x = 1 << 3;
使用指针来访问数组元素。例如:
*(array + i) = 10;
使用宏定义来定义常量和函数。例如:
#define PI 3.14159
使用预处理器指令来控制编译器。例如:
#ifdef DEBUG printf("Debugging mode\n");
使用静态变量来在函数调用之间共享变量。例如:
static int count = 0;
使用枚举类型来定义常量。例如:
enum {RED, GREEN, BLUE};
使用结构体来组织数据。例如:
struct student { char name[20]; int age; };
使用指针来动态分配内存。例如:
int *p = (int*) malloc(sizeof(int));
使用递归函数来解决复杂的问题。例如:
int factorial(int n) { return (n == 0) ? 1 : n * factorial(n-1); }
使用函数指针来调用不同的函数。例如:
void (*function_ptr)(int) = &my_function; function_ptr(10);
使用联合体来在同一内存空间中存储不同的数据类型。例如:
union my_union { int i; float f; };
使用inline函数来提高代码的性能。例如:
inline int square(int x) { return x * x; }
使用可变参数函数来接受不同数量和类型的参数。例如:
int sum(int count, ...) { va_list args; va_start(args, count); int result = 0; for(int i = 0; i < count; i++) { result += va_arg(args, int); } va_end(args); return result; }
使用函数宏来实现代码复用。例如:
#define SQUARE(x) ((x) * (x))
使用goto语句来跳转到程序中的标签。例如:
goto end_of_function; ... end_of_function: return 0;
使用位域来压缩数据。例如:
struct flags { unsigned int flag1: 1; unsigned int flag2: 1; unsigned int flag3: 1; };
使用指针数组来处理字符串。例如:
char *strings[] = {"one", "two", "three"}; printf("%s", strings[1]);
使用多维数组来表示矩阵。例如:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
使用条件编译指令来根据不同的条件编译不同的代码。例如:
#if DEBUG ... #endif
使用typedef关键字来定义自定义类型。例如:
typedef int my_integer;
使用无限循环来创建类似于死循环的代码。例如:
while(1) { ... }
使用do-while循环来确保代码至少执行一次。例如:
do { ... } while(condition);
使用unsigned类型来存储非负数。例如:
unsigned int x = 10;
使用volatile关键字来确保变量被正确地读取和写入。例如:
volatile int x = 10;
使用指针运算符来访问结构体的成员。例如:
struct my_struct { int x; int y; }; struct my_struct *ptr; ptr->x = 10;
使用memcpy函数来复制内存块。例如:
int dest[5]; int src[5] = {1, 2, 3, 4, 5}; memcpy(dest, src, sizeof(int) * 5);
使用条件编译指令来支持不同的操作系统或编译器。例如:
#ifdef _WIN32 ... #endif
使用函数指针数组来执行不同的函数。例如:
void (*functions[3])(int) = {&function1, &function2, &function3}; functions[1](10);
使用带标签的break语句来跳出多层循环。例如:
for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { if(condition) { goto end_of_loop; } } } end_of_loop: ...
使用指针运算符和数组下标来遍历字符串。例如:
char *str = "hello"; for(int i = 0; str[i] != '\0'; i++) { printf("%c\n", str[i]); }
使用__func__预定义宏来获取当前函数的名称。例如:
printf("Function name: %s\n", __func__);
使用函数指针作为函数参数来实现回调函数。例如:
void my_function(int x, void (*callback)(int)) { ... }
使用逗号运算符来执行多个操作。例如:
int x = 1, y = 2, z = (x++, y++, x + y);
(z的值为3,x和y的值分别为2和3)使用union来创建联合体类型,可以在不同的数据类型之间共享内存。例如:
union my_union { int x; float y; };
使用条件运算符(三目运算符)来进行条件判断和赋值。例如:
int x = (condition) ? 10 : 20;
使用静态变量来保留函数调用之间的状态信息。例如:
void my_function() { static int counter = 0; counter++; printf("Counter: %d\n", counter); }
使用inline关键字来将函数的定义嵌入到调用点。例如:
inline int my_function(int x) { return x * x; }
使用#和##预处理运算符来动态地生成标识符和符号。例如:
#define CONCAT(x, y) x ## y
(CONCAT(a, b)将会被替换为ab)