C/C++ |
||
assert()
Functionality of assert() is very simple. It can be briefly described as follows. void assert(int expression); The expression can be any C expression that gives on int result (usually comparision statement). If the expression gives non-negative value (i.e, value >= 0) the assert is doing nothing, but if the expression gives negative value it prints an error message in stderr (i.e, console) and abort(terminate) the program. The keyword here is 'abort(terminate) the program'.
It is usually used in debuging purpose and when you want to make it sure that a certain condition is met before the program to go any further.
It is handy function to use but suggest you to get clear understanding on how it works and why you want to use it. A few bullets below may help you with this.
Example 01 >
#include <assert.h> // you need to include assert.h to use assert() function. #include <stdio.h>
int main() { int x;
x = -1;
assert(x >= 0); // the expression within assert() gives FALSE, so assert() will be triggered
printf("Hello World ! \n");
return 1; }
Example 02 >
#include <assert.h> #include <stdio.h>
int main() { int x;
x = -1;
assert(x >= 0 && "x cannot be a negative value"); // you can put your own message in this way.
printf("Hello World ! \n");
return 1; }
Example 03 >
#define NDEBUG // you can disable assert() by defining NDEBUG. // You have the define this before #include <assert.h>
#include <assert.h> #include <stdio.h>
int main() { int x;
x = -1;
assert(x >= 0 && "x cannot be a negative value");
printf("Hello World ! \n");
return 1; }
Reference :
|
||