Skip to content

Begin with a Contract

The Course
•
45 min study

You already know functions, bounded arrays, pointers, structs, validation and source files. This course adds dynamic storage and stronger API contracts. By Day 7 you will have built a text analyzer that reads lines such as reading 25, stores a growing list of study records, and prints totals grouped by topic. All core practice runs in the browser with prefilled stdin, and no C++ knowledge is needed. Allow about two and a half hours per day, including attempts and debugging.

Start with a small problem that the beginner report hid. Suppose a function reads a new duration into a variable you already use. The input is bad, so the function fails, but it has already written a half-checked value into your variable. Your program now holds a number that nobody validated, and the only clue is a return value you might not have read. Nothing crashed, so the bug stays hidden until a report shows a total that makes no sense.

A contract prevents this by saying, before any code is written, exactly what a function needs and what it promises. In C the compiler checks almost none of it, so the contract lives in a comment, in the function's shape and in your tests.

Predict and run

The function below accepts durations from 1 to 180 minutes. Read the program before pressing Run. Write down its output and explain which statement produces each number.

Predict before running C
#include <stdio.h>

int set_minutes(int value, int *out) {
    if (value < 1 || value > 180) { return 0; }
    *out = value;
    return 1;
}

int main(void) {
    int minutes = 7;
    int ok = set_minutes(0, &minutes);
    printf("%d %d\n", ok, minutes);
    return 0;
}
Check your prediction
Text
0 7

The first number is the result: 0 means the value was rejected. The second number is the old value. Because the guard returns before the assignment, a rejected call leaves minutes exactly as it was.

Three parts of every contract

A useful contract answers three questions:

  • Preconditions are the caller's obligations. Here, out must point to an int the caller is allowed to write. The function cannot check every precondition: it cannot tell whether a non-NULL pointer refers to live storage.
  • Success behavior says what changes. On success, *out holds the accepted value and the function returns 1.
  • Failure behavior says what does not change. On failure, the function returns 0 and *out is untouched.

Write the contract as a comment next to the declaration, so the person calling the function sees it without reading the body:

C
/* Accepts durations 1..180.
   Requires: out points to a writable int.
   Success: stores value in *out and returns 1.
   Failure: returns 0 and leaves *out unchanged. */
int set_minutes(int value, int *out);

A rejected record is not a bug. Malformed text, full storage and unavailable memory are ordinary outcomes that a program must expect, so they get a result value, not a crash.

Validate first, commit last

The order of statements is the contract. Compare a version that writes first and checks afterward:

Write first, check later C
#include <stdio.h>

int set_minutes_early(int value, int *out) {
    *out = value;
    if (value < 1 || value > 180) { return 0; }
    return 1;
}

int main(void) {
    int minutes = 7;
    int ok = set_minutes_early(0, &minutes);
    printf("%d %d\n", ok, minutes);
    return 0;
}
Text
0 0

The result still says "rejected", so a quick test of the return value passes. But the caller's 7 is gone and has been replaced by the invalid 0. That is why every test in this course checks two things: the result, and that the state is unchanged after a failure. The pattern to remember is validate, then commit: do all the checking first, then make every change at the end, when nothing can fail any more.

A precondition the compiler relies on

What if a caller passes NULL for out? Writing through a null pointer is undefined behavior (UB). The C standard places no requirement at all on what happens next. The program might crash, or it might seem to work.

UB is worse than "it might crash", because the compiler is allowed to assume it never happens. Look at this function:

C
int read_minutes(const int *p) {
    int value = *p;      /* undefined if p is NULL */
    if (p == NULL) {     /* the optimizer may delete this check */
        return -1;
    }
    return value;
}

The dereference comes first. A compiler can reason: "if p were NULL, the first line would already be UB, so p is not NULL, so the check is always false." With optimization on, it may remove the check, and your safety net disappears without any warning. The fix is to check before the first use, not after.

For a cheap check like this, a library function should test out == NULL and report failure. You will see the project's record_parse do exactly that. Preconditions that cannot be checked, such as "this pointer refers to live storage", stay in the comment.

The caller has a job too

A return code helps only if someone reads it. This caller ignores it:

Ignore the result C
#include <stdio.h>

int set_minutes(int value, int *out) {
    if (value < 1 || value > 180) { return 0; }
    *out = value;
    return 1;
}

int main(void) {
    int minutes = 7;
    set_minutes(250, &minutes);
    printf("Logged %d minutes\n", minutes);
    return 0;
}
Text
Logged 7 minutes

The function kept its promise: 7 is unchanged. The program still prints a lie, because it reports a record that was never logged. Check the result at the call site and take a different path on failure: count a rejection, print a message, or stop.

Three pieces of syntax this course uses

C beginner did not need these, but the starters from today on do. Each is shorthand for something you already know.

  • typedef gives a type a second name. typedef struct { int minutes; int pages; } Log; lets you write Log log; instead of repeating struct .... typedef enum { LEVEL_SHORT, LEVEL_FULL } Level; names a set of integer constants (0, 1, …) so a function can return Level instead of a bare int.
  • switch picks a branch by comparing one integer value with constant case labels; default catches everything else. Execution starts at the matching label and runs until a break or return. A case without one "falls through" into the next case, which is a classic bug you will meet in Name Failure Outcomes.
  • condition ? a : b, the conditional operator, is an if/else that produces a value: a when the condition is true, b otherwise. Use it for short choices such as picking a word to print.
typedef, switch and ?: together C
#include <stdio.h>

typedef struct {
    int minutes;
    int pages;
} Log;

typedef enum { LEVEL_SHORT, LEVEL_FULL } Level;

const char *level_name(Level level) {
    switch (level) {
    case LEVEL_SHORT:
        return "short";
    case LEVEL_FULL:
        return "full";
    }
    return "unknown";
}

int main(void) {
    Log log = {45, 12};
    Level level = log.minutes >= 30 ? LEVEL_FULL : LEVEL_SHORT;
    printf("%d min is %s\n", log.minutes, level_name(level));
    switch (log.pages) {
    case 0:
        printf("no pages\n");
        break;
    default:
        printf("%d pages\n", log.pages);
        break;
    }
    printf("%s\n", log.pages == 1 ? "one page" : "several pages");
    return 0;
}
Text
45 min is full
12 pages
several pages

Trace it: log.minutes >= 30 is true, so ?: produces LEVEL_FULL, and the switch in level_name returns "full" from the matching case. The second switch finds no case 12, so it runs default, and break stops it there. Delete that default's break and nothing changes, because it is the last case; delete the break after case 0 and set pages to 0, and both lines print. That is fallthrough.

Practice

Exercise

Your turn

A Log holds minutes and pages. Write int update_log(int minutes, int pages, Log *out). It succeeds only when out is not NULL, minutes is in 1..180 and pages is in 1..500. On success, it stores both values and returns 1. On any failure it returns 0 and changes neither field. The starter's main should then print these four lines: update(30, 12): 1 -> 30 min, 12 pages, then update(0, 12): 0 -> 30 min, 12 pages, then update(45, 0): 0 -> 30 min, 12 pages, and finally update NULL: 0.

Your workspace C
#include <stdio.h>

typedef struct { int minutes; int pages; } Log;

/* Write update_log here. */

int main(void) {
    Log log = {7, 7};
    int ok = update_log(30, 12, &log);
    printf("update(30, 12): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    ok = update_log(0, 12, &log);
    printf("update(0, 12): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    ok = update_log(45, 0, &log);
    printf("update(45, 0): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    printf("update NULL: %d\n", update_log(25, 3, NULL));
    return 0;
}
Hint 1: the idea

The third call has a valid duration but invalid pages. If you store the minutes before checking the pages, the report shows 45 instead of 30. All checks must finish before the first write.

Hint 2: a first step

Write only the NULL check and the two assignments, and run. The first and last lines are already right; the middle two are not, because nothing rejects bad values yet. Now add the range checks so that they all run before either assignment, and watch the third line: it is the one that shows whether any field is written too early.

Show one solution
Run the solution C
#include <stdio.h>

typedef struct { int minutes; int pages; } Log;

/* Success: stores both values and returns 1.
   Failure (NULL out, minutes outside 1..180, pages outside 1..500):
   returns 0 and leaves *out unchanged. */
int update_log(int minutes, int pages, Log *out) {
    if (out == NULL || minutes < 1 || minutes > 180 || pages < 1 || pages > 500) {
        return 0;
    }
    out->minutes = minutes;
    out->pages = pages;
    return 1;
}

int main(void) {
    Log log = {7, 7};
    int ok = update_log(30, 12, &log);
    printf("update(30, 12): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    ok = update_log(0, 12, &log);
    printf("update(0, 12): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    ok = update_log(45, 0, &log);
    printf("update(45, 0): %d -> %d min, %d pages\n", ok, log.minutes, log.pages);
    printf("update NULL: %d\n", update_log(25, 3, NULL));
    return 0;
}
Text
update(30, 12): 1 -> 30 min, 12 pages
update(0, 12): 0 -> 30 min, 12 pages
update(45, 0): 0 -> 30 min, 12 pages
update NULL: 0

The single guard means there is no moment when one field is new and the other is old. The || operator evaluates left to right and stops at the first true test, so out == NULL is checked before anything else touches out. The call with valid minutes and invalid pages is the one that catches a write-early bug. Next, you will apply the same care to sizes and counts, where the danger is arithmetic that silently wraps.

Was this article helpful?

Your response is saved on this device.