Re: Verify and expression
* Andrei Alexandrescu (See Website For Email):
Frederick Gotham wrote:
BinglongX posted:
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() );
I prefer this:
bool ok = start_bus();
assert(ok);
, as it separates the "actual" code from the "debugging" code.
That introduces a gratuitous variable. if (!start_bus()) assert(false);
would avoid that.
Ah, learned a new meaning of "gratuitous"... :-) Earlier in life I
maintained that if I didn't learn something new every day, I was getting
old. Now it's, if I don't learn something new every week... So thanks.
I have for some time come to appreciate the Perl style (is it Perl?) of
statements like
doThatThing || die // Some hypothetical language, Perl?
writing things like
doThatThing() || throwX( "Failed to do that thing!" ); // C++
which is very readable -- do that thing or else throw -- and can be
formatted to make the failure reporting code less visually imposing or
to make it stand out, depending on one's preferences and the context.
It would be nice to use essentially the same notation for both
exceptions and assertions; neither should ideally happen, it's just the
seriousness that differs, and in both cases following code shouldn't be
executed -- that's the essential guarantee.
Defining e.g.
define TERMINATE( e ) (assert(( e, false )), std::terminate(), true)
where the 'false' is to assert failure, the 'std::terminate()' is to
ensure termination if NDEBUG is defined (perhaps some feel a "hard"
exception would be more appropriate), and the 'true' is to support the
notation, one can write
doThatThing() || TERMINATE( "Failed to do that thing" );
e.g.
start_bus() || TERMINATE( "The bus failed to start, again." );
But I haven't tried this (just thought of it). Perhaps someone has, and
can offer further comments or insights, or bash the whole idea?
The only problem I see as I write this is that g++ complains about a
do-nothing expression on the left side of the comma operator. Which is
due to the argument to assert doing nothing. For g++ and Visual C++ in
Windows, which both use the MS runtime library, which reports assertion
failure as "Assertion failed: <text> <where>", one way to deal with that is
#define BECAUSE( e ) (void(e), false)
#define TERMINATE( e ) (assert(BECAUSE( e )), std::terminate(), true)
I don't know how that works out (if it does) with other compilers, i.e.
the resulting assertion text when the assertion fails.
Disclaimer: written late at night, or early in the morning. ;-)
Cheers,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]