Re: Stop using assert macro
On Mar 23, 6:24 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Immortal Nephi wrote:
I write custom assertion.
Why?
> The custom assertion is no longer to use
macros. The macros replacement is to use inline function.
Why?
To make it harder to use, and less efficient.
Please comment which macros or inline function is better.
I don't like to place __FILE__ and __LINE__ in inline
function's parameters.
#define DEBUG
#ifdef DEBUG
inline void cassert( bool expr, const char* file, int line, const
char* message )
{
if( !expr )
std::cout << file << "(" << line << ") : Assert failed - Exp=
ression:
" << message << std::endl;
}
#else
inline void cassert( bool expr, const char* file, int line, const
char* message ) {}
#endif
#ifdef DEBUG
#define assert( expr, message ) \
if( !expr ) \
std::cout << __FILE__ << "(" << __LINE__ << ") : Assert fail=
ed -
Expression: " << message << std::endl;
#else
#define assert( expr, message ) ( ( void ) 0 )
#endif
int main()
{
int a = 5;
cassert( 10 < a, __FILE__, __LINE__, "10 < 5" );
assert( 10 < a, "10 < 5" );
Why do you have the text with "5" instead of "a"? Kinda weird
to have the reported expression different from the one you're
checking.
Another advantage of not using macros: you have an additional
possibility of confusing the maintenance programmer.
return 0;
}
None is better. Better is to use macros and let them do their job.
To stop using macros is a noble goal (perhaps), but what if
you have two different assertions both have the control
condition 10 < a, and both have the same expression text "10 <
a", but in two different files or on two different lines of
the same file? You *have to* use __FILE__ and __LINE__ in
that case, don't you? If you don't like to manually insert
those in your source, then you need to use macros which can do
it for you. Not to mention that you have to write your
expression twice, which is the source of maintenance problems.
Patient: "Doctor, when I stop using macros
I don't get automatic __FILE__ and
__LINE__ for my assertion checks."
Doctor: "Well... Don't stop using macros!"
I might add that you can #undef and then #define a macro again.
This is an important feature of assert: it can be defined
differently in different parts of a source file.
--
James Kanze