다음 예제를 보자
#include <stdio.h>
#include <math.h>
#include <assert.h>
int main()
{
double x, y, z;
puts("Enter a pair of numbers (0 0 to quit): ");
while(scanf("%lf%lf", &x, &y) == 2 && (x != 0 || y != 0))
{
z = x * x - y * y;
assert(z >= 0);
printf("Answer is %f\n", sqrt(z));
puts("Next pair of numbers: ");
}
return 0;
}
#include <math.h>
#include <assert.h>
int main()
{
double x, y, z;
puts("Enter a pair of numbers (0 0 to quit): ");
while(scanf("%lf%lf", &x, &y) == 2 && (x != 0 || y != 0))
{
z = x * x - y * y;
assert(z >= 0);
printf("Answer is %f\n", sqrt(z));
puts("Next pair of numbers: ");
}
return 0;
}
결과
Enter a pair of numbers (0 0 to quit):
4 3
Answer is 2.645751
Next pair of numbers:
5 3
Answer is 4.000000
Next pair of numbers:
3 5
assert: assert.c:12: main: Assertion `z >= 0' failed.
일반적으로 인수는 관계식이거나 논리식이다. assert()가 프로그램을 강제로 중지시키면, 먼저 실패한 테스트를 출력하고, 다음으로 테스트를 포함하는 파일명, 라인 번호를 표시나다. 관계식이 false가되면 해당 코드와 경로 및 파일명, 그리고 라인번호를 같이출력한다.
더 멋진 장점은 선언부분에 아래의 정의를 추가한다.
#define NDEBUG
위 의 선언을 정의하면 모든 asert()함수가 비활성화 된다. 당연히 디버깅이 더 필요할시에는 주석처리하고 다시 컴파일 하면 된다. 디버깅용으로 아주 좋을 것이다.
댓글 없음:
댓글 쓰기