Steve555 said:
Is there a standard function or macro that does the same as assert()
(printing the file & line info), but returning without exiting?
I found this in the header; I would try and write my own if I could
decipher it.
#define assert(e) \
(__builtin_expect(!(e), 0) ? __assert_rtn(__func__, __FILE__,
__LINE__, #e) : (void)0)
Is it the #e or (void)0 that means exit? And where does
__builtin_expect come from?
Thanks
Steve
The (void)0 is returned when the assertion succeeds (because, clearly,
__assert_rtn is called when it fails); AFAICT it's simply a meaningless
return value (void because you shouldn't be using the r.v. of assert()).
#e is the "stringification"[1] of e, i.e. it expands to the text of e,
since you want the 'Assert failed...' message to tell you /what/ was
being asserted.
I don't know what __builtin_expect does, but __assert_rtn typically
calls abort(). If you want a 'non-fatal' assertion, I'd suggest
#define s_assert(e) \
(__builtin_expect(!(e), 0) ? fprintf(stderr, "Soft assertion failed,
%s at %s:%s in %s\n", #e, __FILE__, __LINE__, __func__) : (void)0)
but with the following caveats:
* I don't know why __builtin_expect is there in the first place or
whether it's appropriate to keep it.
* fprintf is not async-signal-safe, so don't use this s_assert() in a
signal handler.
Better still, write proper error handling code around everything with
descriptive, meaningful error messages. If the descriptive and
meaningful bit is too much work, another possibility is
#define s_assert(e) \
(__builtin_expect(!(e), 0) ? fprintf(stderr, "Soft assertion failed,
%s at %s:%s in %s\n", #e, __FILE__, __LINE__, __func__), false : true)
which you can use as
if(s_assert(foo))
// do normal stuff
else
// handle the error
Which solution is appropriate will, of course, depend on your individual
requirements (eg. are these asserts purely for debugging, or will they
be retained in production code? The latter is bad practice for asserts
but may not be for soft asserts).
-Edward
Refs:
[1]
http://gcc.gnu.org/onlinedocs/cpp/Stringification.html