Standard preprocessor checks can be very useful to catch programming errors. Nevertheless, these checks can be very limited, as they can only evaluate preprocessor expressions, rather than compile time values like sizeof. Presented here is a small piece of code to create compile time checks

There are many useful cases where checks done at compile time can prevent runtime errors. Consider the following (non-compiling) code:

struct {
    int x;
    int y;
} a;
#if (sizeof(a) != 8)
#error "Struct a is not the right size!"
#endif

Unfortunately this code doesn’t compile. The ‘#if’ statement is evaluated at precompile-time, but sizeof is a compilation instruction. The solution is compile time assertion. A little hack that forces the compiler to evaluate an expression during compilation follows.

CCASSERT – Compile Time Assert Macro
In order to evaluate the expression, the macro will try to define an array with size calculated by predicate. Note that this is legitimate ANSI-C code, so most compilers should support it.

#define CCASSERT(expr) \\
           typedef char ASSERT_CONCAT(constraint_violated_on_line_, __LINE__) \
                               [2*((expr)!=0)-1];
#define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b)
#define ASSERT_CONCAT_(a, b) a##b

Example usage:

#define TOTAL 256
#define SIZE1 122

int arr1[SIZE1]
int arr2[TOTAL - SIZE1];

CCASSERT(sizeof(arr2) == 134 * sizeof(int))

In case the validation fails, the following compile time error will occur:

error: size of array ‘assert_on_line_8’ is negative
Posted by Ami Chayun | | No comments

No Comments »

RSS feed for comments on this post. TrackBack URI

Leave a comment