lovecreatesbeauty said:
Besides printing out for example
" a.out: p113.c:8: main: Assertion `0' failed.
Aborted "
and a switch option NDEBUG, what other benefits does assert() provide
in any scope of designing, debugging/coding and/or testing?
Do you prefer the if statement of the language to the assert MACRO of
the precompiler?
Assert can be your best friend. For example, if instead of:
int
foo(int x, int y)
{ /* Return some function of x and y. Remember, x needs
to be between 5 and 10, and y must be between 15 and 150
or this will segfault!! */
....
}
you write:
int
foo(int x, int y)
{
assert(x > 5 && x <=10);
assert (y >=15 && y<150);
....
}
You get 2 major benefits.
1) Removes the ambiguity inherent in the English description
regarding whether the endpoints are inclusive,
2) When some code is changed so that a caller is using
the wrong arguments, you will be instantly aware of it
when you run, instead of getting a random segfault and
having to track down what caused it.
Also, placing assertions makes it clear to the maintainer
what the coder expected. Any time you expect something
to be true, place an assertion. If it fails, you either have
a coding error somewhere, or your expectation is wrong.
Either is good to know.
Assert is better than if for this type of thing, because it goes
away when you compile your non-debug version. You can
accomplish that with precompiler wrappers around your
if statements, but it is aesthetically unappealing in most
cases.