C++ assert()

Introduction

The assert() preprocessor macro is defined in the library header cassert.

This enables you to test logical expressions in your program.

#include <iostream>
#include <cassert>
int main()/*from   w w w .j av  a 2  s  .  c  om*/
{
  int y {5};

  for(int x {} ; x < 20 ; ++x)
  {
    std::cout << "x = " << x << " y = " << y << std::endl;
    assert(x<y);
  }
}

Switching Off assert() Macros

You can switch off the preprocessor assertion mechanism when you recompile the program by defining NDEBUG:

#define NDEBUG

assert() is for detecting programming errors, not for handling errors at runtime.




PreviousNext

Related