10個C語言小竅門,原文提到是適用C99,其實部分技巧也適用于C89。MSVC沒有驗證過,clang和gcc作者都已經驗證過,大部分C語言開發者都可以嘗試一下。
1. 隱藏三元操作符的中間表達式
// 常用寫法
x = x ? x : 10;
// 簡化寫法
x = x ?: 10;
// 如果x是表達式,簡化寫法可以少一次計算。
2. 矢量坐標系數據結構聲明
typedef union {
struct { float x, y; };
float v[2];
} vec2_t;
typedef union {
struct { float x, y, z; };
struct { vec2_t xy; };
struct { float x_; vec2_t yz; };
float v[3];
} vec3_t;
#define VEC3(x, y, z) {{x, y, z}}
...
vec3_t vec = VEC3(1, 2, 3);
// 靈活多變的訪問方式
float x = vec.x;
vec2_t xy = vec.xy;
float z = vec.v[2];
3. 宏IS_DEFINED
// As used in the linux kernel.
// A macro that expands to 1 if a preprocessor value
// was defined to 1, and 0 if it was not defined or
// defined to an other value.
#define IS_DEFINED(macro) IS_DEFINED_(macro)
#define MACROTEST_1 ,
#define IS_DEFINED_(value) IS_DEFINED__(MACROTEST_##value)
#define IS_DEFINED__(comma) IS_DEFINED___(comma 1, 0)
#define IS_DEFINED___(_, v, ...) v
// #define SOMETHING 1
// 可以用預處理的方式書寫
#if IS_DEFINED(SOMETHING)
...
#endif
// 也可以放在條件語句中
if (IS_DEFINED(SOMETHING)) {
...
}
4. 便利的OpenGL宏(沒用過)
// Not really special, but so useful I thought
// I'll put it here. Can also be used with other
// libraries (OpenAL, OpenSLES, ...)
#ifdef DEBUG
# define GL(line) do { \
line; \
assert(glGetError() == GL_NO_ERROR); \
} while(0)
#else
# define GL(line) line
#endif
// Put GL around all your opengl calls:
GL(glClear(GL_COLORS_MASK));
GL(pos_loc = glGetAttribLocation(prog, "pos"));
5. 數組長度的宏
// 還有人在C語言的項目中不使用這個宏?
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
// 可以這樣使用:
int a[] = {0, 4, 5, 6};
int n = ARRAY_SIZE(a); // n = 4
// 警告,函數參數不可以使用
int func(int a[]) {
int nb = ARRAY_SIZE(a); // Would not work!
}
6. 安全的最小值宏(使用GNU擴展)
#define min(a, b) ({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; \
})
7. 傳遞指針參數
// 假設有一個函數需要傳入3個整數
void func(const int *arg);
// 除了可以使用局部變量
int tmp[] = {10, 20, 30};
func(tmp);
// 還可以使用匿名指針
func( (const int[]){10, 20, 30} )
// 再用宏來處理一下
#define VEC(...) ((const int[]){__VA_ARGS__})
func(VEC(10, 20, 30));
// 同樣適用于結構體或者其他數據類型.
8. 初始化
// 假設有以下結構體
struct obj {
const char *name;
float pos[2];
float color[4];
};
// 讓我們寫一個宏,如下所示
#define OBJ(_name, ...) \
(struct obj) { \
.name = _name, \
.color = {1, 1, 1, 1}, \
__VA_ARGS__ \
};
// 現在我們可以使用這個宏來創建一個新的對象。
// This one with color defaulted to {1, 1, 1, 1}.
struct obj o1 = OBJ("o1", .pos = {0, 10});
// This one with pos defaulted to {0, 0}.
struct obj o2 = OBJ("o2", .color = {1, 0, 0, 1});
9. X宏(沒用過,不知道使用場景)
// Define this once.
#define SPRITES \
X(PLAYER, "atlas_0.png", {0, 0, 128, 128}) \
X(ENEMY0, "atlas_0.png", {128, 0, 128, 128}) \
X(ENEMY1, "atlas_2.png", {0, 0, 64, 64}) \
...
// Create an enum with all the sprites.
emum {
#define X(n, ...) SPR_##n,
SPRITES
#undef X
}
// Create an array with all the sprites values.
struct {
const char *atlas;
int rect[4];
} sprites[] = {
#define X(n, a, r) [SPR_##n] = {a, r},
SPRITES
#undef X
};
// Many other possibilities...
10. 狀態機助手
// This is a great trick.
// Instead of:
int iter(int state) {
switch (state) {
case 0:
printf("step 0\n");
return 1;
case 1:
printf("step 1\n");
return 2;
case 2:
printf("step 2\n");
return 3;
case 3:
return -1;
}
}
// We can define:
#define START switch(state) { case 0:
#define END return -1; }
#define YIELD return __LINE__; case __LINE__:;
// And now the function can be written
int iter(int state) {
START
printf("step 0\n");
YIELD
printf("step 1\n");
YIELD
printf("step 2\n");
END
}
// It is possible to go totally wild with
// this one.
我是咕咕雞,一個還在不停學習的全棧工程師。
熱愛生活,喜歡跑步,家庭是我不斷向前進步的動力。