What is the "assert" function?


I've been studying OpenCV tutorials and came across the assert function; what does it do?

6/25/2013 6:51:38 PM

Accepted Answer

assert will terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.

For example:

assert(length >= 0);  // die if length is negative.

You can also add a more informative message to be displayed if it fails like so:

assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");

Or else like this:

assert(("Length can't possibly be negative! Tell jsmith", length >= 0));

When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assert statements by defining the NDEBUG macro, usually with a compiler switch. The corollary of this is that your program should never rely on the assert macro running.

// BAD


// Watch out! Depends on the function:

// Here's a safer way:
int ret = foo();

From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).

12/10/2017 3:51:29 PM

The assert computer statement is analogous to the statement make sure in English.


Take a look at

assert() example program in C++

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.


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

void analyze (char *, int);

int main(void)
   char *string = "ABC";
   int length = 3;

   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);

void analyze(char *string, int length)
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */

/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3

The assert() function can diagnose program bugs. In C, it is defined in <assert.h>, and in C++ it is defined in <cassert>. Its prototype is

void assert(int expression);

The argument expression can be anything you want to test--a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr and aborts program execution.

How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement

assert(interest_rate >= 0); at locations in the program where interest_rate is used. If the variable ever does become negative, the assert() macro alerts you. You can then examine the relevant code to locate the cause of the problem.

To see how assert() works, run the sample program below. If you enter a nonzero value, the program displays the value and terminates normally. If you enter zero, the assert() macro forces abnormal program termination. The exact error message you see will depend on your compiler, but here's a typical example:

Assertion failed: x, file list19_3.c, line 13 Note that, in order for assert() to work, your program must be compiled in debug mode. Refer to your compiler documentation for information on enabling debug mode (as explained in a moment). When you later compile the final version in release mode, the assert() macros are disabled.

 int x;

 printf("\nEnter an integer value: ");
 scanf("%d", &x);

 assert(x >= 0);

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

Enter an integer value: 10

You entered 10.

Enter an integer value: -1

Error Message: Abnormal program termination

Your error message might differ, depending on your system and compiler, but the general idea is the same.


Stuff like 'raises exception' and 'halts execution' might be true for most compilers, but not for all. (BTW, are there assert statements that really throw exceptions?)

Here's an interesting, slightly different meaning of assert used by c6x and other TI compilers: upon seeing certain assert statements, these compilers use the information in that statement to perform certain optimizations. Wicked.

Example in C:

int dot_product(short *x, short *y, short z)
  int sum = 0
  int i;

  assert( ( (int)(x) & 0x3 ) == 0 );
  assert( ( (int)(y) & 0x3 ) == 0 );

  for( i = 0 ; i < z ; ++i )
    sum += x[ i ] * y[ i ];
  return sum;

This tells de compiler the arrays are aligned on 32-bits boundaries, so the compiler can generate specific instructions made for that kind of alignment.


C++11 N3337 standard draft

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. 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 simply as

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

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics The assert macro



#include <assert.h>
void assert(scalar expression);


2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.


3 The assert macro returns no value.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]