Joseph Turian:
I've been using assert liberally throughout my code.
Brilliant.
Then, upon compiling with -NDEBUG, I found that my program had
different output.
Why? Because -NDEBUG disables assert, but I had (at least) one assert
with a side-effect.
Can someone recommend a safer mechanism for assertions? e.g. one that
determines the const-ness of what is being checked?
First of all, there's nothing wrong with "assert". The only problem is your
malusage of it.
Here's a quick idea to find the asserts which have side-effects.
Firstly, make a copy of the entire project, i.e. all the code files. Do a
"Find and Replace", replacing each occurence of "assert" with "assertBAD".
Compile the program and you should get a list of lines on which the
unidentified identifier "assertBAD" was used. Save the compiler output to a
text file (i.e. the file and line number errors).
Now, use your compiler options to define the following macro across the
entire program:
#define assertBAD(expr) expr
Now, re-compile the program. If you have the appropriate warning level set,
the compiler will warn you of any redundant expression-statements. Here's
an example of a Before and After:
Before:
int main()
{
assert(i % 10);
}
After:
int main()
{
i % 10;
}
The compiler can see plainly that the expression-statement is useless, and
will warn you. Again, save the compiler output to a file.
Now compare the two lists. The ones that are on the first list but which
aren't on the second are the ones which have side-effects. Of course you'll
get a few false-positives such as:
UserDefinedType obj;
assert(obj.IsOpen());
, but hopefully they'll be in the minority.
--
Frederick Gotham