Compile-Time Assertions
Arrays are not just a convenience feature. Since their size is fixed at compile time, they can be used in compile-time checks that would not otherwise be possible. For example, suppose I have an enumeration, and I want to associate a string with each enumerated value. Listing Three works but is not very robust because it gives incorrect results if I later add a new value to the enum but forget to update the array. By making a couple of minor changes to the code (Listing Four), I can make the compiler double-check my work. COMPILE_TIME_ASSERT is a macro that takes a compile-time constant as its argument. (For an implementation, see the complete source code for this article; refer to "Resource Center," page 5.) If the argument is True, the macro has no effect. If it is False, the macro produces a compile-time error. In Listing Four, the assertion is that the enum and the array have the same number of elements. Therefore, if the enum and array should ever get out of sync, the compiler lets me know about it.
// in Color.h enum Color { red, blue, green, }; // in Color.cpp const char* color_names[] = { "red", "blue", "green" }; const char* get_name(Color c) { return color_names[c]; }
// in Color.h enum Color { red, blue, green, last_color // one-past-the-end value; must be last }; // in Color.cpp const char* color_names[] = { "red", "blue", "green", "invalid color" }; const char* get_name(Color c) { return color_names[c]; } COMPILE_TIME_ASSERT( COUNTOF(color_names) == last_color + 1 );