前言
整理自個人筆記的 C 語言核心語法速查表,涵蓋資料型別、關鍵字、運算子優先序、標準庫常用函式、前置處理器指令,適合面試複習與開發隨時查閱。
一、基本資料型別與大小(32 位系統典型值)
| 型別 | 位元數 | 範圍 | 格式字串 |
char | 8 | -128~127 或 0~255 | %c / %hhd |
short | 16 | -32,768~32,767 | %hd |
int | 32 | -2,147,483,648~2,147,483,647 | %d |
long | 32/64 | 平台相關 | %ld |
long long | 64 | -9.22e18~9.22e18 | %lld |
float | 32 | ~7 位有效數字 | %f |
double | 64 | ~15 位有效數字 | %lf |
void* | 32/64 | 位址 | %p |
二、關鍵字分類(C99/C11 新增標註)
- 型別:
char short int long float double signed unsigned void _Bool _Complex
- 儲存類別:
auto register static extern thread_local
- 控制流:
if else switch case default for while do break continue goto return
- 結構/聯合/列舉:
struct union enum typedef
- 其他:
const volatile restrict inline _Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local
三、運算子優先序與結合性(高→低)
1 () [] -> . 左→右
2 ++ -- + - ! ~ * & (type) sizeof 右→左
3 * / % 左→右
4 + - 左→右
5 << >> 左→右
6 < <= > >= 左→右
7 == != 左→右
8 & 左→右
9 ^ 左→右
10 | 左→右
11 && 左→右
12 || 左→右
13 ?: 右→左
14 = += -= *= /= %= &= ^= |= <<= >>= 右→左
15 , 左→右
四、常用標準庫函式速查
| 標頭檔 | 常用函式 |
<stdio.h> | printf scanf puts gets fgets fprintf fscanf fopen fclose fread fwrite fseek ftell |
<stdlib.h> | malloc free calloc realloc exit abort system qsort bsearch abs labs div rand srand |
<string.h> | strcpy strncpy strcat strncat strcmp strncmp strlen strchr strstr memcpy memmove memset |
<math.h> | sin cos tan sqrt pow log log10 exp fabs floor ceil fmod |
<time.h> | time clock difftime strftime gmtime localtime |
<ctype.h> | isalpha isdigit isspace toupper tolower |
<assert.h> | assert |
<stdarg.h> | va_start va_arg va_end va_copy |
五、前置處理器指令
#define MACRO(x) ... // 宏定義
#undef MACRO // 取消宏
#include <header> // 系統標頭
#include "header.h" // 使用者標頭
#if defined(DEBUG) // 條件編譯
#elif defined(RELEASE)
#else
#endif
#pragma once // 防重複包含(非標準但廣泛支援)
#pragma pack(n) // 結構對齊
#error "message" // 編譯期報錯
#warning "message" // 編譯期警告(GCC/Clang)
六、常見陷阱備忘
sizeof(arr) 在函式參數中退化為指標大小
- 浮點數不可直接
== 比較,需用 fabs(a-b) < EPS
malloc 失敗回傳 NULL,必須檢查
strcpy/strcat 不檢查邊界,優先用 snprintf/strncpy(注意結尾)
- 變長參數函式需
va_start(ap, last_fixed),va_arg(ap, type) 取值,va_end(ap) 收尾
七、實用片段:絕對值不分支實作
int abs_branchless(int x) {
int mask = x >> 31; // 算術右移:負數全 1,非負全 0
return (x ^ mask) - mask; // 負數:~x + 1 = -x
}