Assertion --assertion macro

You can insert assertions into your source code using the assert macro.

assert (condition)

If the condition of the assert macro is true, nothing happens. If the condition is false, an error message will be output and the program will terminate. If core dump output is enabled, core dump output is also output. This is useful if you want to check that a value is what you expect.

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

int main (void) {
  int32_t num = 3;
  
  // Check that num is greater than 1
  assert (num> 1);
  
  printf("%d\n", num);
}

This is the output result. Since "num" is larger than "1", it will be executed normally.

3

Let's change "num" to "-1".

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

int main (void) {
  int32_t num = -1;
  
  // Check that num is greater than 1
  assert (num> 1);
  
  printf("%d\n", num);
}

This is the output result for gcc.

a: a.c: 9: main: Assertion `num> 1'failed.
Aborted (core dumped)

ls command and grep command, a core dump is also output.

$ls | grep core
core.28560

Think of a core dump as a file that contains information about debugging your program. We will discuss how to debug a program using a core dump elsewhere.

Remove assert macros

The assert macro can be removed by specifying the NDEBUG macro at compile time. This is useful if you only use the assert macro when debugging and you don't want to include the assert macro in the final product output.

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

int main (void) {
  int32_t num = -1;
  
  // Check that num is greater than 1
  assert (num> 1);
  
  printf("%d\n", num);
}

Let's define and execute the "NDEBUG macro" with the "-D" option of gcc as follows. The assert macro part is not executed.

gcc -DNDEBUG -o a a.c && ./a

Associated Information