Re: Verify and expression
BinglongX wrote:
If I do not want to depend on MFC, there is assert(exp) but I could not
find verify(exp) or similar things in standard C/C++. So I just define
it myself:
#include <assert.h>
#ifdef NDEBUG
#define verify(exp) (exp)
#else
#define verify(exp) ( (exp) || (assert(0),0) )
#endif
Its direct usage is like this:
verify( start_bus() ); // assert(0) if start_bus() fails
This definition is different from MFC's, because the macro actually
"returns" the evaluated expression, so that I can write code like this:
bool ok = verify( start_bus() );
ok will have the return value of start_bus(), no matter in debug or
non-debug version. (in non-debug version, only when the assert handler
can resume the running, of course.)
In my code, I had something like this:
bool ok = check_function_args(...);
if( !ok )
{
assert(false); // alert for programming error.
return false; // do not go beyond in runtime as well.
}
And I can now replace it with much more short one, without a temporary
auto variable:
if( !verify( check_function_args() ) )
return false;
My question is, is there any pitfall in this macro definition? I assume
if this is really useful there would have been it somewhere?
There are always pitfalls to using a macro - name collisions for
example. After all, "verify" is not that uncommon a word (especially in
programming). So it's easy to anticipate that the macro name "verify"
could very well end up conflicting with a "verify" identifier already
in use in some program.
Since the C++ way is to use inline functions instead of macros wherever
practical, why not just declare the non-debug verify() like so:
inline bool verify(bool inFlag) { return inFlag; }
With optimizations enabled, any C++ compiler should be able to compile
verify() away to a nop; so the inline verify() should be just as
efficient as the macro verify() - but still have the advantages of
proper name scoping and type safety that the macro verify() lacks.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]