RSS

再習C言語:3.25 assert マクロ

06 7月

3.25 assert マクロ

assert は自動テストのための機能の一つである。例えば、あるバグを修正したときその修正が他のコードに悪影響があり、以前と違った結果を出力するかもしれえない。

特に大きなプログラムでは何人もの人が関わっているため、共通で使われている関数などを修正したとき、いちいち他の人にテストを依頼するのは現実的でない。

assert をプログラム内の要所に埋め込んでおけば、期待値と現実で得られた値を比較して異なる場合は、エラーメッセージを出力して停止する。

次の例は tan(x) で角度 x が 90 度のときは無限大になってしまうので、assert() で角度 x が 90 度を渡さないようにトラップをかけている。

/* assert.c */
#include <stdio.h>
#include <math.h>
#include <assert.h>
#define PI 3.1415926

int main() {
  for (float x = 0.0; x <= 90.0; x++) {
    assert(x == 90.0);
    printf("%f %f\n", x, tan(x / 180.0 * PI));
  }
}
実行例
$ ./bin/assert
assert: assert.c:9: main: Assertion `x == 90.0' failed.
Aborted (core dumped)
$

そして、assert はデバッグ時のみ適用し、本番時には無効にできる。NDEBUG が assert.h の前に定義されていると assert は無効になる。 次のように gcc の -D オプションでも NDEBUG を設定可能である。

$ gcc -o assert -D NDEBUG assert.c -lm
/* assert.c */
#include <stdio.h>
#include <math.h>

#define NDEBUG
#include <assert.h>
#define PI 3.1415926

int main() {
  for (float x = 0.0; x <= 90.0; x++) {
    assert(x == 90.0);
    printf("%f %f\n", x, tan(x / 180.0 * PI));
  }
}
 
コメントする

投稿者: : 2023/07/06 投稿先 C, gcc

 

タグ:

コメントを残す