[c++] Static assertions

An assertion statement is used at runtime to verify that an assumption holds true. Typically assert is only used in debug builds, while release builds switch it out completely.

Keep in mind that while an assertion is no substitute for proper error checking, it is useful for a quick verification of low level assumptions. If you design a function with the expectation that the provided pointer will always be valid; then adding an assert will warn the caller when they aren’t playing by the same rules that you are.

int get_nth_char( const char* str, int idx ) {
    assert( str ); // program stops here if str is invalid
    if ( idx < 0 ) return -1;
    return str[ idx ];

Static assertions take assert a step further and provide sanity checks at compile time. While static assertions can only operate on known compile time data it is still really useful. A good example is the packing of network data where it is vital that the data is packed correctly and is of the right size. Not only will a static assert verify this. It will also catch the case if it gets changed at a later stage.

#pragma pack( push, 1 )
struct PktData {
    char b1;
    char b2;
#pragma pack( pop )

BOOST_STATIC_ASSERT( 2 == sizeof(PktData) );

While the static assert in the above code is courtesy of boost, the upcoming C++0x standard will also include this functionality.

Leave a Reply