AgentSkillsCN

c-programming

基于现代 C 标准(C99/C11/C17/C23)以及 K.N. King 所著《C 程序设计:现代方法》的教学理念,提供专家级的 C 语言编程指导。适用于用户编写 C 代码、调试 C 程序、咨询 C 语法或语义、探讨 C 数据类型、指针、数组、字符串、结构体、联合体、枚举、预处理器、C 标准库、内存管理、文件 I/O、位运算,或程序组织等相关场景。此外,当提及 gcc、clang、包含 C 文件的 Makefile、段错误调试、未定义行为、指针算术、malloc/free、printf/scanf 格式化、头文件、链接性、存储期、翻译单元,或任何 C 标准库头文件(如 stdio.h、stdlib.h、string.h、math.h 等)时,亦会触发相关提示。内容涵盖从基础概念到函数指针、抽象数据类型以及底层编程等进阶主题,全面覆盖 C 语言的各个层面。

SKILL.md
--- frontmatter
name: c-programming
description: >
  Expert-level C programming assistance based on modern C standards (C99/C11/C17/C23)
  and the pedagogical approach of "C Programming: A Modern Approach" by K.N. King.
  Use when the user is writing C code, debugging C programs, asking about C syntax or
  semantics, discussing C data types, pointers, arrays, strings, structs, unions,
  enums, the preprocessor, the C standard library, memory management, file I/O,
  bitwise operations, or program organization. Also triggers on mentions of gcc, clang,
  Makefile with C files, segfault debugging, undefined behavior, pointer arithmetic,
  malloc/free, printf/scanf formatting, header files, linkage, storage duration,
  translation units, or any C standard library header (stdio.h, stdlib.h,
  string.h, math.h, etc.). Covers the full language from fundamentals through
  advanced topics like function pointers, abstract data types, and low-level programming.

C Programming Expert

Language Standards

StandardYearKey Additions
C89/C901989/1990Original ANSI/ISO standard
C991999_Bool, // comments, VLAs, designated initializers, restrict, inline, <stdbool.h>, <stdint.h>, mixed declarations/code, long long
C112011_Generic, _Static_assert, _Atomic, <threads.h>, anonymous structs/unions, aligned_alloc, bounds-checking (__STDC_LIB_EXT1__)
C172018Bug fixes only — no new features
C232024nullptr, typeof, constexpr, #embed, _BitInt, [[attributes]], auto type inference, <stdbit.h>

Default to C99 as baseline (widely supported, most practical). Note C23 features when relevant.

Compile with: gcc -std=c99 -Wall -Wextra -pedantic (or -std=c11, -std=c17, -std=c23).

Compilation Model

code
source.c  →  preprocessor  →  translation unit  →  compiler  →  object file  →  linker  →  executable
(.c)         (cpp/gcc -E)     (expanded .c)        (gcc -c)     (.o)           (gcc)      (a.out)

Each .c file is compiled independently. Headers (.h) are textually included by the preprocessor. The linker resolves cross-file references using external linkage.

Type System Quick Reference

Integer types (minimum guaranteed sizes)

TypeMinimum bitsTypical sizeFormat specifier
char81 byte%c / %hhd
short162 bytes%hd
int164 bytes%d
long324 or 8 bytes%ld
long long64 (C99)8 bytes%lld

All integer types exist in signed (default) and unsigned variants. Use <stdint.h> for exact-width types: int8_t, int16_t, int32_t, int64_t, uint*_t.

Floating-point types

TypeTypical precisionFormat specifier
float~7 digits%f / %e / %g
double~15 digits%f / %e / %g
long double~18-33 digits%Lf / %Le / %Lg

Other types

TypeHeaderNotes
_Bool / bool<stdbool.h> (C99)true=1, false=0
size_t<stddef.h>Unsigned, result of sizeof
ptrdiff_t<stddef.h>Signed, pointer difference
NULL<stddef.h>Null pointer constant

Operator Precedence (high to low)

PrecedenceOperatorsAssociativity
1() [] -> . ++(post) --(post)Left
2++(pre) --(pre) + - (unary) ! ~ * & sizeof (type)Right
3* / %Left
4+ -Left
5<< >>Left
6< <= > >=Left
7== !=Left
8&Left
9^Left
10|Left
11&&Left
12||Left
13?:Right
14= += -= *= /= %= <<= >>= &= ^= |=Right
15,Left

Common pitfall: & / ^ / | bind looser than == / !=. Always parenthesize: if ((x & MASK) == EXPECTED).

Undefined Behavior — Critical Rules

C has undefined behavior (UB) that the compiler may exploit for optimization. Key UB to avoid:

  1. Signed integer overflow — use unsigned or check before operations
  2. Dereferencing NULL or dangling pointers — always validate
  3. Out-of-bounds array access — no runtime checks in C
  4. Using uninitialized variables — always initialize
  5. Double free or use-after-free — set pointers to NULL after free()
  6. Violating strict aliasing — don't cast between incompatible pointer types (use memcpy or unions)
  7. Modifying a variable twice between sequence points — e.g., i = i++ is UB
  8. Shifting by negative or >= bit-width1 << 32 is UB for 32-bit int
  9. Dividing by zero — check divisor
  10. Misaligned pointer access — use memcpy for unaligned reads

Reference Documents

Load these as needed based on the specific topic:

TopicFileWhen to read
Types & Expressionsreferences/fundamentals.mdBasic types, constants, literals, expressions, operators, type conversions, sizeof, implicit promotions (Ch 2, 4, 7)
Control Flowreferences/control-flow.mdif/else, switch, while, for, do-while, break, continue, goto, comma operator (Ch 5, 6)
Formatted I/Oreferences/formatted-io.mdprintf/scanf conversion specifiers, field widths, precision, flags, format string safety (Ch 3)
Arrays & Stringsreferences/arrays-strings.mdArray declaration/initialization, multidimensional arrays, VLAs, string literals, string.h functions, string idioms (Ch 8, 13)
Functionsreferences/functions.mdFunction definition, prototypes, parameters, return values, recursion, inline (C99), _Noreturn (Ch 9)
Program Organizationreferences/program-organization.mdScope, linkage, storage duration, header files, multi-file builds, #include guards, information hiding, ADTs (Ch 10, 15, 19)
Pointersreferences/pointers.mdPointer basics, &/*, arithmetic, pointer-array relationship, pointers as parameters, const and pointers, pointer to pointer (Ch 11, 12)
Advanced Pointersreferences/advanced-pointers.mdmalloc/calloc/realloc/free, linked lists, function pointers, void*, qsort/bsearch callbacks, abstract data types (Ch 17)
Preprocessorreferences/preprocessor.md#define, macros with parameters, #/#, conditional compilation, #include, #pragma, predefined macros (Ch 14)
Structs, Unions & Enumsreferences/structs-unions-enums.mdstruct declaration/access, nested structs, self-referential structs, unions, enumerations, typedef, flexible array members (Ch 16)
Low-Level Programmingreferences/low-level.mdBitwise operators, bit-fields, volatile, memory layout, alignment, union type punning, endianness (Ch 20)
Declarationsreferences/declarations.mdDeclaration syntax, storage classes (auto/static/extern/register), type qualifiers (const/volatile/restrict), initializers, reading complex declarations (Ch 18)
File I/Oreferences/file-io.mdStreams, fopen/fclose, text vs binary mode, fread/fwrite, fseek/ftell, error handling, temporary files (Ch 22)
Internationalizationreferences/internationalization.mdLocales, setlocale, wide characters (wchar_t), multibyte/wide conversion, <wchar.h>, <wctype.h>, Unicode (char16_t/char32_t), UTF-8 (Ch 25)
Standard Libraryreferences/standard-library.mdLibrary overview, <stdlib.h>, <math.h>, <ctype.h>, <errno.h>, <assert.h>, <signal.h>, <setjmp.h>, <stdint.h>, C99/C11 additions (Ch 21, 23-27)