Coding Style & Conventions
C's minimal syntax and lack of built-in structure (no mandatory naming rules, no enforced formatting, no package/module system) mean consistent style matters more here than in many modern languages. With fewer built-in guardrails to catch structural mistakes, a readable, consistent codebase is one of the few things standing between "maintainable" and "unmaintainable" C.
Common Conventions
Element | Common convention |
|---|---|
Variables and functions |
|
Macros and constants |
|
Struct/type names | Often |
Brace placement | K&R style (opening brace on the same line) and Allman style (opening brace on its own line) both exist -- see below |
Indentation | Commonly 4 spaces or a tab (Linux kernel style famously uses 8-wide tabs) -- either is fine as long as it is consistent |
Header guards |
|
K&R vs Allman Brace Style
// K&R style: opening brace stays on the same line as the statement.
int add(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Allman style: opening brace goes on its own line.
int add(int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}Automating Style with clang-format
.clang-format configuration file and run clang-format as part of the build or a pre-commit hook. This removes style disagreements from code review entirely — the tool enforces brace placement, indentation, spacing, and line wrapping automatically and identically for every contributor.# A minimal .clang-format example BasedOnStyle: LLVM IndentWidth: 4 BreakBeforeBraces: Attach ColumnLimit: 100