Style, contracts, and code review
Use names, invariants, scope, control flow, guidelines, and review to make program assumptions visible.
In this chapter8 sections
Readable code helps another person check your reasoning. Names, small interfaces, and visible validation steps make assumptions easier to find. We will connect style choices to reviewable behavior, then distinguish conventions from language rules.
1. Names should expose the unit and responsibility
Prefer names that distinguish bytes from elements, capacity from logical length, and a candidate value from accepted state. A length parameter should say what it counts. A module prefix reduces ordinary identifier collisions; a macro prefix also reduces preprocessing collisions. Follow the implementation’s reserved-identifier rules instead of inventing private-looking underscore names.
2. Make the precondition and update order visible
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
enum { SCORE_LIMIT = 100 };
struct Score { unsigned points; };
static bool add_points(struct Score *score, unsigned increment)
{
if (score == NULL || score->points > SCORE_LIMIT) return false;
if (increment > SCORE_LIMIT - score->points) return false;
score->points += increment;
return true;
}
int main(void)
{
struct Score score = { .points = 73 };
bool accepted = add_points(&score, 7);
assert(accepted && score.points == 80);
bool rejected = add_points(&score, 30);
assert(!rejected && score.points == 80);
return 0;
}
The named limit explains the domain. The first check establishes the current state before subtraction; the second proves the increment will fit the intended bound. Only then does the state change. A rejected request preserves the old value. The structure remains exposed, so the function defensively rejects an invalid existing points value rather than pretending the type alone enforces the invariant.
Keep functions focused enough that their ownership and failure paths fit in a review. Small does not mean hiding every line behind another helper. Separate operations when evaluation order matters, initialize objects before use, and keep a variable’s scope close to the code that needs it. Comments should explain a reason or contract, not merely restate an assignment in English.
3. Write control flow around the domain
#include <assert.h>
#include <stddef.h>
#include <string.h>
enum Mode { MODE_READ, MODE_WRITE };
static const char *mode_name(enum Mode mode)
{
switch (mode) {
case MODE_READ: return "read";
case MODE_WRITE: return "write";
default: return NULL;
}
}
int main(void)
{
const char *name = mode_name(MODE_READ);
assert(name != NULL && strcmp(name, "read") == 0);
const char *unknown = mode_name((enum Mode)99);
assert(unknown == NULL);
return 0;
}
A default handles unrecognized input in this interface, while named cases document the recognized domain. C does not generally require every switch to contain default or prove exhaustive coverage. Compiler checks and a project standard can add policies. When adding an enumerator, assess its transition and error behavior rather than merely silencing a warning.
4. Formatting conventions and coding standards have different roles
Brace placement, indentation width, line length, and naming style are team choices unless a chosen standard imposes a rule. A formatter can make those mechanical choices consistent. Avoid presenting one brace style as a C language requirement. Review meaningful changes separately from large formatting-only changes so contracts and behavior remain visible.
MISRA C and SEI CERT C are distinct guideline families with their own scope, editions, and adoption processes. They are not interchangeable with ISO C conformance or a formatter preset. A project adopting a guideline needs the actual applicable text, deviations where allowed, and suitable review/tool evidence; citing its name is not certification.
5. A review follows the data and the failure paths
Start at an input boundary. Ask which type, range, count, lifetime, and ownership facts become established, and where each is used. Follow early exits and cleanup, then examine shared-state synchronization. Check required return values according to the API rather than applying an indiscriminate “every ignored return is wrong” rule. Record deliberate target assumptions and make regression tests explain the intended contract.
This completes the expanded Correctness & care unit. Revisit the expanded Language details and C in context chapters to connect these contracts with declaration rules and version choices. Revisit earlier examples using these reasoning tools; marking a chapter read remains your own progress marker, not a claim that every advanced contract has been mastered.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.1, 6.4.2.1, 6.8.4.2, 7.1.3. Stable core rules used for the C17 baseline; not the final ISO publication.
- SEI CERT C: public standard
- MISRA Compliance:2020 — official process guidance
Before you move on
- Readable names and interfaces make assumptions easier to inspect.
- Validation and state updates should have a deliberate, reviewable order.
- Style guidelines complement the language rules and the application contract.
Keep these ideas separate
- Consistent formatting / Correct behavior
- A neatly formatted function can still violate bounds, lifetime, range, or application requirements.
Which naming or control-flow change would make a function’s rejection path easier to review?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, formatting automatically releases resources.
Formatting does not perform runtime cleanup.
- No. They help communicate a contract that still needs to be designed and followed.
✓ Correct reasoning. Readable code makes reasoning easier without making every operation correct automatically.
- Yes, a descriptive pointer name proves its lifetime.
A name is not evidence that an object is still alive.
General
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.
Because C's minimal restrictions leave enormous room for individual style, most serious C codebases adopt a formal convention:
- Layout styles. The terse K&R style (opening brace on the same line as its statement) originates from Kernighan and Ritchie's own book; Allman style puts every brace on its own line; the Linux kernel coding style is a widely referenced, tab-based variant of K&R with strict rules on line length and naming.
- Safety-critical standards. MISRA C, originally developed for the automotive industry, restricts or forbids constructs prone to undefined or hard-to-review behavior — for instance, banning certain uses of pointer arithmetic, or requiring every
switchto include adefaultcase. CERT C is a comparable secure-coding standard, focused on eliminating exploitable vulnerabilities rather than functional-safety concerns specifically. - General best practices. Consistent naming and indentation, avoiding unexplained "magic numbers" in favor of named constants or enums, keeping each function focused on a single task, minimizing the scope and lifetime of variables, and always checking the return value of any function that can fail.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.