Visual C++: Assert in Release Mode

Problem

In Visual C++, assertions are disabled in Release mode and enabled in Debug mode of the solution. I find assertions to be cheap and effective means of capturing programmer errors and would like assertions to be invoked during Release mode too.

Solution

assert is a macro and its existence during compilation is controlled by the definition of the NDEBUG identifier. If NDEBUG is defined, assertions are disabled. As you can guess, by default, NDEBUG is defined in Release mode.

So, to enable assertions in Release mode, go to the project properties → C/C++ → Preprocessor → Preprocessor Definitions and remove NDEBUG.

Tried with: Visual C++ 2008

CUDA: Assertion in Kernel Code

Assertions are very useful to catch programmer mistakes. Sadly, there is no mechanism to trigger an actual assert() in CUDA kernel code. Lung Sheng Chien showed me a simple way to create a assert for CUDA kernel code using macros:

// Macro definition
#define CudaAssert( X ) if ( !(X) ) { printf( "Thread %d:%d failed assert at %s:%d!", blockIdx.x, threadIdx.x, __FILE__, __LINE__ ); return; }

// Usage

#include <cstdio>

__global__ void fooKernel( const int* vals )
{
    // ...
    CudaAssert( ( vals[ threadIdx.x ] < 0 ) && "Input data not valid!" );
    // ...
}

Note:

  • To be able to use printf() in kernel code, the compiler must be compiling for a GPU architecture of sm_20 or later.
  • A cudaThreadSynchronize() call is needed immediately after the kernel call to flush the buffer that printf() writes to.

Tried with: CUDA 3.2 and Visual Studio 2008

C++: Assertion with Information

I find it useful to include the comment or information about an assertion in the assert() expression itself.

Code like:

// Check for invalid oxygen level
assert(oxyLevel < OXYGEN_MAX);

can easily be rewritten as:

assert((oxyLevel < OXYGEN_MAX) && "Invalid oxygen levels!!!");

This works because a C string constant is always true (non-zero).

I like the second version since it folds the comment information into the assert() expression. Also, when the assertion fails, Visual Studio pops up a dialog where you can see the entire assert() expression (which includes your informative string):