[C] assert 매크로

꾸준희
|2018. 11. 26. 13:44
728x90
반응형



assert 매크로는 assert.h 헤더 파일에 정의되어 있으며 정해진 조건에 맞지 않는 경우 프로그램을 중단한다. 


1. assert에 지정한 조건식이 거짓(false)일 때 프로그램을 중단

2. assert에 지정한 조건식이 참(true)일 때는 프로그램을 계속 실행


단, Visual Studio 에서는 Debug 모드에서만 작동하며 Release 모드에서는 동작하지 않음





포인터가 NULL이면 프로그램을 중단하는 예제


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <assert.h>     // assert가 정의된 헤더 파일

void copy(char *dest, char *src)
{
    assert(dest != NULL);    // dest이 NULL이면 프로그램 중단
    assert(src != NULL);     // src가 NULL이면 프로그램 중단

    strcpy(dest, src);       // 문자열 복사
} 

int main()
{
    char s1[100];
    char *s2 = "Hello, world!";

    copy(s1, s2);     // 정상 동작

    copy(NULL, s2);   // NULL이 들어갔으므로 프로그램 중단
    // Assertion failed: dest != NULL, file c:\project\assert\assert\assert.c, line 8
    
    return 0;
}




참고자료 : https://dojang.io/mod/page/view.php?id=764

728x90
반응형