CCoding Style & Conventions

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

snake_case -- e.g. total_count, read_file()

Macros and constants

ALL_CAPS_WITH_UNDERSCORES -- e.g. MAX_BUFFER_SIZE, #define PI 3.14159

Struct/type names

Often snake_case with a _t suffix for typedef'd types -- e.g. typedef struct { ... } point_t;

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

#ifndef HEADER_H / #define HEADER_H / #endif, or the widely-supported #pragma once

K&R vs Allman Brace Style

C
// 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;
    }
}
Both styles are widely used in real, respected codebases (K&R is the Linux kernel's style; Allman is common in many Windows and embedded codebases). Neither is objectively correct — what matters far more than which one you pick is applying it consistently throughout a single project.
Automating Style with clang-format
Rather than debate style manually or rely on developers to remember conventions, most modern C projects check in a .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.

YAML
# A minimal .clang-format example
BasedOnStyle: LLVM
IndentWidth: 4
BreakBeforeBraces: Attach
ColumnLimit: 100
When contributing to an existing project, match its style, not your own preference
Consistency across a codebase is more valuable than any individual style choice. If a project already uses Allman braces and 8-space tabs, write your contribution the same way even if you personally prefer K&R and 4 spaces -- mixed styles within one file or project make diffs noisier and code harder to scan.