Compile time assertions

Petter Reinholdtsen pere at HUNGRY.COM
Wed Feb 2 17:37:44 EST 2005


In the November 2004 issue of the C/C++ Users Journal, there is a nice
article on "Compile-Time Assertions" by Ralf Holly.  He explain the
consept of asserts what trigger error at compile time if the assert
expression is failse, and go through a number of examples.

The point of such asserts are to document assumsions done in the code
in such a way that the compiler will report if the assumsions no
longer holds, instead of waiting until the program is executed (like
normal asserts do).

If the code assume the 'char' type is signed, it could be documented
with code like this:

  assert_static(-1 == (char)-1);

Or, if one assume the sizeof(int) equals the sizeof(void*), one could
document it in the code like this:

  assert_static(sizeof(int) == sizeof(void*));

The article lists several ways to implement such compile time assert.
Here are the examples, if the order they are presented in the article:

  #if 0
  #define assert_static(e) 1/(e)
  #elif 0
  #define assert_static(e) switch(0){case 0: case (e):;}
  #elif 0
  #define assert_static(e) { char assert_static__[(e) ? 1 : -1];}
  #else
  #define assert_static(e) do{enum{ assert_static__ = 1/(e)};}while (0)
  #endif

Would it be an idea to introduce such asserts into the mapserver code,
and use it to document and enforce the assumtions used by the
programmer?

The background for this question is the observation that the code for
example seem to assume that 'char' is an signed type, while ANSI C89
do not garantee this.  I discovered this assumsion when
resultCacheMemberObj.classindex was compared with 0 (classindex > 0),
and the compiler I used at the time complained that this test would
always be true.  The same compiler would refuse to compile code
containing 'assert_static(-1 == (char)-1);', so the problem would be
detected at compile time instead of at run time.



More information about the mapserver-dev mailing list