Namaran

Code daily. Without assist.

2026-10-10

withdraw.c

#include <assert.h>
#include <stdio.h>

struct account { long balance; };

static void withdraw(struct account *a, long amount) {
    assert(0 < amount && amount <= a->balance);      // precondition
    const struct account *before = a;
    a->balance -= amount;
    assert(a->balance == before->balance - amount);  // postcondition
}

int main(void) {
    struct account acc = {100};
    withdraw(&acc, 30);
    withdraw(&acc, 50);
    printf("%ld\n", acc.balance);
}

withdraw は口座から amount を引き出す関数で、事前条件と事後条件を assert で表明しています。残高 100 の口座から 30 と 50 を引き出すこのプログラムは、本来なら 20 を出力します。いまは最初の withdraw(&acc, 30) で事後条件の assert が失敗し、何も出力せずに異常終了します。

Answer

Wrong

const struct account *before = a;
a->balance -= amount;
assert(a->balance == before->balance - amount);  // postcondition

before は a と同じ口座を指すポインタで、引き出す前の残高を写し取ってはいません。a->balance -= amount のあとで before->balance を読むと、返ってくるのはすでに 70 になった残高です。事後条件は 70 == 70 - 30 を確かめることになり、事前条件で amount が正だと分かっている以上、この比較は必ず偽です。そのため assert は withdraw を呼ぶたびに失敗し、abort でプログラムを止めます。

Right

const struct account before = *a;
a->balance -= amount;
assert(a->balance == before.balance - amount);   // postcondition

before を構造体の値として宣言すると、初期化の時点で *a の中身がコピーされます。その後に a->balance を変えても before.balance は 100 のままなので、事後条件は 70 == 100 - 30 を確かめて通ります。2回目も 20 == 70 - 50 で通り、20 が出力されます。事後条件で変更前の値と比べるには、ポインタではなく値そのものを取っておく必要があります1。

  1. Eiffel では事後条件の中に old balance と書くと、呼び出し前の値を言語が取っておいてくれます。C にはこの仕組みがないので、ここのように自分でコピーを取ります。