0% found this document useful (0 votes)
93 views3 pages

Debugging with Assertions

The assert macro is used to test expressions and terminate the program if the expression is false. It prints an error and calls abort. Assertions are useful for debugging variable values. The assert macro tests if x is less than y, and if not it prints an error and terminates the program. Defining NDEBUG ignores subsequent assertions so debugging can be disabled without removing each assertion.

Uploaded by

Yking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views3 pages

Debugging with Assertions

The assert macro is used to test expressions and terminate the program if the expression is false. It prints an error and calls abort. Assertions are useful for debugging variable values. The assert macro tests if x is less than y, and if not it prints an error and terminates the program. Defining NDEBUG ignores subsequent assertions so debugging can be disabled without removing each assertion.

Uploaded by

Yking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ASSERTIONS

 assert macro defined in the <cassert> header file


 test the value of an expression.
 If the value of the expression is 0(false), then
assert prints an error message and calls function
abort (of the general utilities library - <cstdlib> ) to
terminate program execution.
 This is a useful debugging tool for testing if a
variable has a correct value.
 For example , variable x should be less than y . An
assertion may be used to test the value. The
statement would be
 assert( x < y );
 If x is greater than y, an error message containing
the line number and file name is printed, and the
program terminates.
 The programmer may then concentrate on this
area of the code to find the error.
 If the symbolic constant NDEBUG is defined,
subsequent assertions will be ignored. Thus, when
assertions are no longer needed, i.e., when
debugging is complete, the line
#define NDEBUG
is inserted in the program file rather than deleting
each assertion manually
#include<iostream>
#include<cassert>
using namespace std;

int main()
{
int x = 0, y = 5;
for( x =0; x < 10; x++)
{
cout << "x= " << x << " y= " << y << endl;
assert(x < y);
}
return 0;
}

You might also like