Search code examples
c++if-statementexceptionassert

Why can't I use an if statement instead of using assert in C++?


Since assert simply checks if the statement in its parameter holds true or not, why don't we simply use an if condition to check that?

Usage of assert

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

Usage of if

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

Can anybody point out the difference between the two and advantages of using one over the other?

Also, why do most people prefer assert over if here?


Solution

  • An assert should never fire in correct code. If it does, there is a bug in your code, and it needs to be fixed. So with a function like this:

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

    You are saying that a null pointer should never be passed to this function, and if it is, then the code that passed it is incorrect.

    However, with your function here:

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

    You are saying that it is okay to pass a null pointer to this function, it just doesn't do anything in that case.

    A more appropriate function to compare your assert version with would be something like this:

    void print_number(int* somePtr) {
      if (somePtr == NULL)
          std::abort();
      printf ("%d\n",*somePtr);
    }
    

    That does essentially the same thing as assert (though without the useful diagnostic message). The difference here is that asserts disappear if NDEBUG is defined. This function (with the if, then abort) would make the check under all circumstances.