How to test if your ASSERT macro is compiled out
March 4th, 2006I am often interested in how specific code works in different build configurations. In the case of a custom ASSERT macro, I want to make sure that it does not evaluate any expression in builds where it is disabled (i.e. it is 'compiled out'). The technique I use is the following:
Let's assume CHECK_EQUALS is a macro in your test framework that checks if it's two inputs are equal. ASSERT behaves as usual. Let's also assume, your build system somewhere defines ASSERTS_ENABLED in those builds where this is so desired. Here is some code:
- TEST(AssertBehavesCorrectlyAcrossBuildConfigs)
- {
- int a = 0;
- ASSERT(a = 100);
- #ifdef ASSERTS_ENABLED
- CHECK_EQUALS(a, 100);
- #else
- CHECK_EQUALS(a, 0);
- #endif
- }
What's happening here? The expression inside ASSERT contains code with a side effect. If the ASSERT macro is defined to do anything, the side effect is that a is being set to 100. The expression evaluates to true, and no harm is done. Otherwise a will stay at 0, in which case we can safely say that ASSERT does not evaluate the expression.