Page | 51
assert should be chosen so that it holds true only if the program is operating as intended. The macro evaluates the
assert argument and, if the argument expression is false (0), alerts the user and halts program execution. No action is taken if the argument is true (nonzero. When an assertion fails, an output message with the following text is generated assertion failed in file
name inline
num where
name is the name of the source file and
num is the line number of the assertion that failed. The liberal use of assertions throughout your programs can catch errors during development. A good rule of thumb is that you should write assertions for any assumptions you make. For example, if you assume
that an argument is not NULL, use an assertion statement to check for that condition. void checkerror_strcpy(char * src, char *dst)
{ assert(src!=dst); assert(src!=NULL); assert(dst!=NULL);
} Here we check that some assumptions we made for
strcpy are true. After we are sure there are no errors in the software, we can easily disable all assertion checks adding
"#define NDEBUG" before where
"#include < assert.h >" appears in the source code.
Share with your friends: