Thursday, December 29, 2011

C tricks: compile time assert in pure C

In my last post about compile time assert, I concluded that with new C++11 static_assert the issue is finally resolved and everyone is encouraged to use it now. Sadly that was too quick to close the discussion, because one case is still actual, namely compile time assert in pure C, where static_assert is not available.
If you recall the C++ solution, it used template specialization, which forced the compiler to evaluate boolean expression at compile time. There are no templates in C, so it won't work as well. But there are typedefs and array size still must be computed at compile time and it can't be negative, so we can start for that.
The following implementation is credited to RBerteig and his answer on StackOverflow. The code I came up with is similar, but ignores the line number. So I'll just copy his version and comment it a little bit.
CASSERT macro takes two parameters: the predicate to be tested and the file name identifier. The latter is optional and aims to clear the error message, the client can pass any error message there. _impl_PASTE is a just helper macro to concatenate the identifier name from file and line number.
Here's how the CASSERT is used in a client code (file demo.c):
And that's it: the problem is solved for both C++ and C. C++11 assertion is obviously prettier, but the code above provides a nice fallback when one has to code pure C.





No comments:

Post a Comment