Good Code
The good version accepts a const struct Review *, so the compiler helps enforce that the score check is read-only.
Lesson 04
Mark read-only pointers as const so callers and reviewers know a check will not mutate shared state.
#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;
}#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;
}The good version accepts a const struct Review *, so the compiler helps enforce that the score check is read-only.
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.