|
|
|
|
|
|
|
When writing your program, you will often know deep down in your soul that something is true: a function has a certain value, a pointer is valid, and so forth. It is the nature of bugs that what you know to be true might not be true under some conditions. For example, you know that a pointer is valid, yet the program crashes. assert() can help you find this type of bug, but only if you make it a regular practice to use assert() statements liberally in your code. Every time you assign or are passed a pointer as a parameter or function return value, be sure to assert that the pointer is valid. Any time your code depends on a particular value being in a variable, assert() that it is true. |
|
|
|
|
|
|
|
|
There is no penalty for frequent use of assert() statements; they are removed from the code when you undefine debugging. They also provide good internal documentation, reminding the reader of what you believe is true at any given moment in the flow of the code. |
|
|
|
|
|
|
|
|
It is not uncommon to find that a bug appears only after the assert() statements are removed. This is almost always due to the program unintentionally depending on side effects of things done in assert()s and other debug-only code. For example, if you write |
|
|
|
|
|
|
|
|
when you mean to test whether x == 5, you will create a particularly nasty bug. |
|
|
|
|
|
|
|
|
Let's say that just prior to this assert(), you called a function that set x equal to 0. With this assert() you think you are testing whether x is equal to 5; in fact, you are setting x equal to 5. The test returns true, because x = 5 not only sets x to 5, but returns the value 5; and because 5 is non-zero, the test evaluates to true. |
|
|
|
|
|
|
|
|
After you pass the assert() statement, x really is equal to 5 (you just set it!). Your program runs just fine, and you're ready to ship it, so you turn debugging off. Now the assert() disappears and you are no longer setting x to 5. Because x was set to 0 just before this, it remains at 0 and your program breaks. |
|
|
|
|
|
|
|
|
In frustration, you turn debugging back on, but hey! Presto! The bug is gone. Once again, this is rather funny to watch, but not to live through, so be very careful about side effects in debugging code. If you see a bug that only appears when debugging is turned off, take a look at your debugging code with an eye out for nasty side effects. |
|
|
|
|
|