C

Lesson 04

Const correctness for read paths

Mark read-only pointers as const so callers and reviewers know a check will not mutate shared state.

Good Code

src/review_score.c
#include <stdbool.h>

struct Review {
    int score;
};

bool review_score_is_passing(const struct Review *review)
{
    // const promises this check will not mutate the review.
    if (review == NULL) {
        return false;
    }

    return review->score >= 70;
}

Bad Code

review_score.c
#include <stdbool.h>

struct Review {
    int score;
};

bool review_score_is_passing(struct Review *review)
{
    // A read check that rewrites state surprises callers.
    if (review->score < 0) {
        review->score = 0;
    }

    return review->score >= 70;
}

Review Notes

What to review

Good Code

The good version accepts a const struct Review *, so the compiler helps enforce that the score check is read-only.

Bad Code

The bad version receives a mutable pointer and normalizes negative scores during a predicate call. A caller asking a question gets state mutation as a hidden side effect.

Takeaways

  • Const is part of the API contract in C; it separates read-only review paths from functions that may change data.