YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Correctness & careChapter 67 of 73

Style, contracts, and code review

Use names, invariants, scope, control flow, guidelines, and review to make program assumptions visible.

5 min readIntermediateC17 baseline
Offline reading
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

Complete C17 program
#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

Complete C17 program
#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

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.
Explain it in your own words

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.

Can clear naming and indentation replace an ownership contract?
Read the explanation for every choice
  1. Yes, formatting automatically releases resources.

    Formatting does not perform runtime cleanup.

  2. 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.

  3. 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 switch to include a default case. 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.

CHAPTER 67 / 73

In this chapter

Style, contracts, and code review

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping