I’d like to add compile time asserts into the following C++ code (compiled with Visual C++ 9):
//assumes typedef unsigned char BYTE;
int value = ...;
// Does it fit into BYTE?
if( 0 <= value && value <= UCHAR_MAX ) {
BYTE asByte = static_cast<BYTE>( value );
//proceed with byte
} else {
//proceed with greater values
}
The problem is UCHAR_MAX and BYTE are independent typedefs and when this code is ported it can happen that they get out of sync and code will break. So I wanted to do something like this:
compileTimeAssert( sizeof( BYTE ) == sizeof( UCHAR_MAX ) );
but VC++9 produces “negative subscript” error while compiling that – sizeof( UCHAR_MAX ) happens to be 4, not 1.
How can I achieve the compile-time check I want?
You can test in the compile-time assert that
( (1 << (sizeof(BYTE)*CHAR_BIT)) - 1 ) == UCHAR_MAX.(I assume that you’re not asking how to do a static assert – there are several ways, see here)