Using the assert() to test whether x < y C++ example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Using the assert() function to test whether x < y in C++ programming

To show: How to use the assert() function to assert a condition in C++ programming

 

// assert() macro, DEBUG and NDEBUG example

// NDEBUG will disable assert() and DEBUG will enable assert().

#define DEBUG

#include <iostream>

using namespace std;

#include <cassert>

 

int main(void)

{

int x, y;

 

// tell user if NDEBUG is defined and do assert

#if defined(NDEBUG)

cout<<"NDEBUG is defined. Assert disabled,\n";

#else

cout<<"NDEBUG is not defined. Assert enabled.\n";

#endif

 

// prompt user some test data...

cout<<"Insert two integers: ";

cin>>x>>y;

cout<<"Do the assert(x < y)\n";

 

// if x < y, it is OK, else this program will terminate...

assert(x < y);

if(x<y)

{

cout<<"Assertion not invoked because "<<x<<" < "<<y<<endl;

cout<<"Try key in x > y, assertion will be invoked!"<<endl;

}

else

cout<<"Assertion invoked, program terminated!"<<endl;

return 0;

}

 

Output example:

 

NDEBUG is not defined. Assert enabled.

Insert two integers: 3 4

Do the assert(x < y)

Assertion not invoked because 3 < 4

Try key in x > y, assertion will be invoked!

Press any key to continue . . .

 

NDEBUG is not defined. Assert enabled.

Insert two integers: 10 7

Do the assert(x < y)

Assertion failed: x < y, file c:\amad\myprog\myprog\myechosrc.cpp, line 26

 

with the following Debug error message box.

 

 

 

 

C and C++ Programming Resources | C & C++ Code Example Index