Using assert.h

Linux Distribution
C Compiler
a shell interface
My Setup:
Debian GNU/Linux
Today, i will be going over an extremely useful standard library header called
assert.h . Assert.h is a header file which defines one specific function:

 void assert(scalar expression);

The assert macro puts diagnostic tests into programs. It expands to a void
expression and when it is executed, if the expression is false, the assert macro
writes information about the particular call that failed. This usually includes
the text of the argument, name of the source file, the source line number and the
name of the enclosing function. After it is finished, it then calls the abort
function. The internal workings of the assert function relies on a macro that
is user defined, this is NDEBUG. If NDEBUG is defined as a macro name at the
point in the source file where assert.h is included, the assert macro is defined
as such:

 #define assert(ignore) ((void)0)

I had to implement this for my Operating System project and this is how i did

#ifndef LIBC_ASSERT_H_
#define LIBC_ASSERT_H_ 1

#define assert(exp)\

#ifdef __cplusplus //if c++
    extern "C"{
#ifndef _NEED_NDEBUG
#ifdef NDEBUG
#define assert(expression)        ((void) 0)
#else //NDEBUG
#undef assert(expression)
#define __VAL(x) #x
#define STR(x) __VAL(X)
void __assert(char*);
#define assert(expression) ((expression) ? ((void)0) : \
        __assert(FILE-":"-STR(LINE_)"" #expression))

#define NEED_NDEBUG 1
#endif // NDEBUG

#endif //NEED_ASSERT

#ifdef __cplusplus //if c++

#endif //HAVE ASSERT

#endif //assert.h

#include "../include/assert.h"
#include "../include/stdio.h"
#include "../include/stdlib.h"

void __assert(char *mesg){
    puts("-- assertion failed\n");

Lets try out an example!

/* The assert() macro. */

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

int main(int argc, char *argv[])
    int x;
    printf("\nEnter an integer value: ");
    scanf("%d", &x);

    assert(x >= 0);

    printf("You entered %d.\n", x);
    return 0;

Compile this down, and run it, and try inputting a negative number.

One thought on “assert.h

Leave a Reply