An assert() statement allows you to directly encode assumptions you make. For example, if char *p is a parameter to a function, and you have assumed that the function is never called with a NULL value for p, then use the statement
at the start of the function. These statements are useful for debugging your code, as they quickly identify when an assumption has been violated. Most compilers remove assert() statements automatically when a final, "release" version of the code is being compiled, so they do not have an adverse affect on performance.Some Do's and Don'ts for assert()
Don't use assert() in place of required error checking. For example:
FILE *fp ;
fp = fopen("somefile","rw");
assert(fp != (FILE *)NULL);Since files routinely cannot be opened (the file is missing, or the user doesn't have the required permission to open the file), you should instead use an 'if' statement to check if fp is NULL, and warn the user if it is. You don't want the program to terminate just because a file wasn't found!
Don't write assert statements with "side effects". For example
assert(i++ == n);is problematic ... the program behaves differently in "release" versions, because the assert() statements are removed and i never gets incremented!
Use assert() before accessing a variable about which you are making an assumption (I can't tell you how many times I've seen something like
*p = 5 ;
assert(p != (int *)NULL);
If p is NULL, this will die with a seg fault error before the assert() statement catches the error)
While there are not hard and fast rules about when to take a section of code an move it into a separate function, the following quidelines might help:
This section applies mostly to C/C++.
if (p == (Sighandler *)-1)
if (p != (int *)NULL)