(1)自定义bool变量
由于C语言中没有bool变量,我们可以自定义一个,然后放在全局的头文件中。
typedef enum{ false = 0, true = 1} bool;
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
(3)求最大值、最小值
#define MAX(x, y) ((x) >= (y) ? (x) : (y))#define MIN(x, y) ((x) >= (y) ? (y) : (x))
(4)空循环防错写法
#define DO_NO_THING()
#include#define DO_NO_THING()int main(int argc, char* argv[]){ int number = 34; while (number++ == 123) { DO_NO_THING(); } return 0;}
(5)两层for循环防错写法
for (row = 0; row < MAX_ROWS; row++){ for (col = 0; col < MAX_COLUMNS; col++) { table[row][col]; // do_something(); }}
#define SET_BIT(x, n) (x |= (1 << n)) // 将x的第n位置1#define CLR_BIT(x, n) (x &= ~(1 << n)) // 将x的第n位清0#define GET_BIT(x, n) ((x >> n) & 0x01) // 取得x的第n位的值
#include#define SET_BIT(x, n) (x |= (1 << n))#define CLR_BIT(x, n) (x &= ~(1 << n))#define GET_BIT(x, n) ((x >> n) & 0x01)int main(int argc, char* argv[]){ char ch = 0x84; printf("%d\n", ch); SET_BIT(ch, 3); printf("%d\n", ch); CLR_BIT(ch, 3); printf("%d\n", ch); printf("%d\n", GET_BIT(ch, 0)); // 0表示最低位 printf("%d\n", GET_BIT(ch, 1)); printf("%d\n", GET_BIT(ch, 2)); printf("%d\n", GET_BIT(ch, 3)); return 0;}
(7)打印一维数组
void printArray(int arr[], int cnt){ int i = 0; for (i = 0; i < cnt; i++) { printf("%d ", arr[i]); } printf("\n");}
(8)打印二维数组
#includevoid printArray2D(int *arr, int rowCnt, int colCnt){ int row = 0; int col = 0; for (row = 0; row < rowCnt; row++) { for (col = 0; col < colCnt; col++) { printf("%d ", *(arr + row * colCnt + col)); } printf("\n"); }}int main(int argc, char* argv[]){ int ia[2][4] = { { 2, 7, 2, 6}, { 5, 3, 9, 1} }; printArray2D(&ia[0][0], 2, 4); //printArray2D(ia, 2, 4); 可以实现功能,但是会有警告,因为指针的类型不同 return 0;}
待续...