views:

2643

answers:

9

I'm tidying up some older code that uses 'magic numbers' all over the place to set hardware registers, and I would like to use constants instead of these numbers to make the code somewhat more expressive (in fact they will map to the names/values used to document the registers).

However, I'm concerned that with the volume of changes I might break the magic numbers. Here is a simplified example (the register set is more complex):

const short mode0 = 0;
const short mode1 = 1;
const short mode2 = 2;

const short state0 = 0;
const short state1 = 4;
const short state2 = 8;

so instead of :

set_register(5);

we have:

set_register(state1|mode1);

What I'm looking for is a build time version of:

ASSERT(5==(state1|mode1));

Update

@Christian, thanks for the quick response, I'm interested on a C / non-boost environment answer too because this is driver/kernel code.

@all, Thanks for the informative answers throughout

+7  A: 

Checkout boost's static assert

Christian.K
I use this all over our code. Its even caught people doing silly things that would have caused unexplained but major havok once or twice.
+7  A: 

You can roll your own static assert if you don't have access to a third-party library static assert function (like boost):

#define STATIC_ASSERT(x) \
    do { \
        const static char dummy[(x)?1:-1] = {0};\
    } while(0)

The downside is, of course, that error message is not going to be very helpful, but at least, it will give you the line number.

Alex B
Nice improvisation, thanks! In my build environment I hit the error:Error: #257: const variable "dummy" requires an initializerSo I changed this to const static char dummy[(x)?1:-1]={0};If you agree/update this I'll mark this as answered, thanks again.
tonylo
+3  A: 

The common, portable option is

#if 5 != (state1|mode1)
#    error "aaugh!"
#endif

but it doesn't work in this case, because they're C constants and not #defines.

You can see the Linux kernel's BUILD_BUG_ON macro for something that handles your case:

#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

When condition is true, this becomes ((void)sizeof(char[-1])), which is illegal and should fail at compile time, and otherwise it becomes ((void)sizeof(char[1])), which is just fine.

ephemient
The kernel folks have noticed that this doesn't handle non-const expressions as well as they'd like, but efforts to replace it [ such as http://lkml.org/lkml/2008/8/17/92 and http://lkml.org/lkml/2008/9/2/170 ] haven't been accepted yet.
ephemient
+3  A: 

There's also a very thorough examination of STATIC_ASSERT techniques in Alexandrescu's Modern C++ Design.

jonner
+4  A: 

Try:

#define STATIC_ASSERT(x, error) \
do { \
    static const char error[(x)?1:-1];\
} while(0)

Then you can write:

STATIC_ASSERT(a == b, a_not_equal_to_b);

Which may give you a better error message (depending on your compiler).

Andreas Magnusson
Ahh... you beat me too it! :-)
Kevin
+13  A: 
Kevin
I have something similar here:http://www.atalasoft.com/cs/blogs/stevehawley/archive/2007/10/29/disgusting-c-ism.aspx
plinth
I like what you do with the msg parameter; I may have to add that capability to mine. I'll also have to test mine on gcc. I wonder if you changed the '2' to a '-1' in your conditional char array declaration, wouldn't that have to cause an error on gcc? Then you could get rid of the gcc special case.
Michael Burr
+3  A: 

Any of the techniques listed here should work and when C++0x becomes available you will be able to use the built-in static_assert keyword.

jwfearn
+2  A: 

If you have Boost then using BOOST_STATIC_ASSERT is the way to go. If you're using C or don't want to get Boost here's my c_assert.h file that defines (and explains the workings of) a few macros to handle static assertions.

It's a bit more convoluted that it should be because in ANSI C code you need 2 different macros - one that can work in the area where you have declarations and one that can work in the area where normal statements go. There is a also a bit of work that goes into making the macro work at global scope or in block scope and a bunch of gunk to ensure that there are no name collisions.

STATIC_ASSERT() can be used in the variable declaration block or global scope.

STATIC_ASSERT_EX() can be among regular statements.

For C++ code (or C99 code that allow declarations mixed with statements) STATIC_ASSERT() will work anywhere.

/*
    Define macros to allow compile-time assertions.

    If the expression is false, an error something like

        test.c(9) : error XXXXX: negative subscript

    will be issued (the exact error and its format is dependent
    on the compiler).

    The techique used for C is to declare an extern (which can be used in
    file or block scope) array with a size of 1 if the expr is TRUE and
    a size of -1 if the expr is false (which will result in a compiler error).
    A counter or line number is appended to the name to help make it unique.  
    Note that this is not a foolproof technique, but compilers are
    supposed to accept multiple identical extern declarations anyway.

    This technique doesn't work in all cases for C++ because extern declarations
    are not permitted inside classes.  To get a CPP_ASSERT(), there is an 
    implementation of something similar to Boost's BOOST_STATIC_ASSERT().  Boost's
    approach uses template specialization; when expr evaluates to 1, a typedef
    for the type 

        ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed<true>) >

    which boils down to 

        ::interslice::StaticAssert_test< 1>

    which boils down to 

        struct StaticAssert_test

    is declared. If expr is 0, the compiler will be unable to find a specialization for

        ::interslice::StaticAssert_failed<false>.

    STATIC_ASSERT() or C_ASSERT should work in either C or C++ code  (and they do the same thing)

    CPP_ASSERT is defined only for C++ code.

    Since declarations can only occur at file scope or at the start of a block in 
    standard C, the C_ASSERT() or STATIC_ASSERT() macros will only work there.  For situations
    where you want to perform compile-time asserts elsewhere, use C_ASSERT_EX() or
    STATIC_ASSERT_X() which wrap an enum declaration inside it's own block.

 */

#ifndef C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546
#define C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546

/* first some utility macros to paste a line number or counter to the end of an identifier
 * this will let us have some chance of generating names that are unique
 * there may be problems if a static assert ends up on the same line number in different headers
 * to avoid that problem in C++ use namespaces
*/

#if !defined( PASTE)
#define PASTE2( x, y) x##y
#define PASTE( x, y)  PASTE2( x, y)
#endif /* PASTE */

#if !defined( PASTE_LINE)
#define PASTE_LINE( x)    PASTE( x, __LINE__)
#endif /* PASTE_LINE */

#if!defined( PASTE_COUNTER)
#if (_MSC_VER >= 1300)      /* __COUNTER__ introduced in VS 7 (VS.NET 2002) */
    #define PASTE_COUNTER( x) PASTE( x, __COUNTER__)   /* __COUNTER__ is a an _MSC_VER >= 1300 non-Ansi extension */
#else
    #define PASTE_COUNTER( x) PASTE( x, __LINE__)      /* since there's no __COUNTER__ use __LINE__ as a more or less reasonable substitute */
#endif
#endif /* PASTE_COUNTER */



#if __cplusplus
extern "C++" {   // required in case we're included inside an extern "C" block
    namespace interslice {
        template<bool b> struct StaticAssert_failed;
        template<>       struct StaticAssert_failed<true> { enum {val = 1 }; };
        template<int x>  struct StaticAssert_test { };
    }
}
    #define CPP_ASSERT( expr) typedef ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed< (bool) (expr) >) >  PASTE_COUNTER( IntersliceStaticAssertType_)
    #define STATIC_ASSERT( expr)    CPP_ASSERT( expr)
    #define STATIC_ASSERT_EX( expr) CPP_ASSERT( expr)
#else
    #define C_ASSERT_STORAGE_CLASS extern                  /* change to typedef might be needed for some compilers? */
    #define C_ASSERT_GUID 4964f7ac50fa4661a1377e4c17509495 /* used to make sure our extern name doesn't collide with something else */
    #define STATIC_ASSERT( expr)   C_ASSERT_STORAGE_CLASS char PASTE( PASTE( c_assert_, C_ASSERT_GUID), [(expr) ? 1 : -1])
    #define STATIC_ASSERT_EX(expr) do { enum { c_assert__ = 1/((expr) ? 1 : 0) }; } while (0)
#endif /* __cplusplus */

#if !defined( C_ASSERT)  /* C_ASSERT() might be defined by winnt.h */
#define C_ASSERT( expr)    STATIC_ASSERT( expr)
#endif /* !defined( C_ASSERT) */
#define C_ASSERT_EX( expr) STATIC_ASSERT_EX( expr)



#ifdef TEST_IMPLEMENTATION
C_ASSERT( 1 < 2);
C_ASSERT( 1 < 2);

int main( )
{
    C_ASSERT( 1 < 2);
    C_ASSERT( 1 < 2);

    int x;

    x = 1 + 4;

    C_ASSERT_EX( 1 < 2);
    C_ASSERT_EX( 1 < 2);



    return( 0);
}
#endif /* TEST_IMPLEMENTATION */
#endif /* C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 */
Michael Burr
+3  A: 

There is an article by Ralf Holly that examines different options for static asserts in C.

He presents three different approaches:

  • switch case values must be unique
  • arrays must not have negative dimensions
  • division by zero for constant expressions

His conclusion for the best implementation is this:

#define assert_static(e) \
    do { \
        enum { assert_static__ = 1/(e) }; \
    } while (0)
pesche