Boost logo

Boost :

Subject: [boost] suggestion on assertion macros
From: DE (satan66613_at_[hidden])
Date: 2010-03-12 12:10:09


there were a discussion recentrly about verifying arguments of
assertion macros while checks are turned off

i've got an idea of how to check the argument(s) and guarantee zero
code size and runtime overhead

suppose we have a canonical macro 'assert()'
while compiling with NDEBUG macro defined it expands to nothing which
may cause annoying compiler warnings (like 'var isn't referenced')

assert() checks a condition i.e. the argument must be convertible to
bool
then we can write

  #define assert(cond) sizeof(cond)

but to check if the arg converts to bool we can write something like

  #define assert(cond) sizeof(bool(cond))

which may or may not expand to some code (i.e. machine instructions)

to ensure zero overhead i suggest the following scheme:

  #ifdef NDEBUG
  typename<size_t s> struct dummy_for_assert;
  #define my_assert(cond)\
    typedef dummy_for_assert<sizeof(bool(cond))> typedef_dummy_for_assert
  #elif
  #define my_assert(cond) assert(cond)
  #endif
  
i hope you got the idea
by the way the typedef may be enclosed in a scope in order not to mess
around:

  #define my_assert(cond)\
    do {\
      typedef dummy_for_assert<sizeof(bool(cond))> t;\
    } while(false)

although all this looks like a big kludge i believe more advanced
programmers would make it work very well (and even make it idiomatic)

if that already has been discussed sorry for wasting your time

--
Pavel

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk