Search code examples
c++macrosassert

Disabling assert macro in C++


I'm trying to disable the assert macro in C++ in this way:

#include <stdio.h>      /* printf */
#include <assert.h>     /* assert */

#define NDEBUG

void print_number(int* myInt) {
  assert (myInt != NULL);
  printf ("%d\n", *myInt);
}

int main ()
{
  int a = 10;
  int * b = NULL;
  int * c = NULL;

  b = &a;

  print_number (b);
  print_number (c);

  return 0;
}

The official website says that if I define NDEBUG, all the assert macro will be disable. This way doesn't work. Can you tell me how fix it?


Solution

  • The NDEBUG define controls the definition of the assert macro, not its expansion. In order for it to be effective, you need to define it before the macro itself is defined, which happens in assert.h.

    There are two ways to achieve that:

    • put the #define NDEBUG before the line that says #include <assert.h>; or
    • define NDEBUG on the command line, by doing something like:
    cc -DNDEBUG main.c
    

    Perhaps you should also take a step back and consider why you are trying to disable assertions. After all, the assertions are there for a reason, so unless you are running on a 40MHz SPARCstation, you should probably not be disabling them.