While reviewing Visual C++ codebase I found a following strange thing. A run-time assert (which is check the condition and throw an exception if the condition is violated) was used in a case when the condition could be evaluated at compile time:
assert( sizeof( SomeType ) == sizeof( SomeOtherType ) );
clearly the compiler will evaluate the condition and replace the code that will effectively be either
assert( true );
which does nothing or
assert( false );
which throws an exception every time control passes through that line.
IMO a compile-time assert should have be used instead for the following reasons:
- it would expose the condition violation earlier - at compile time - and
- it would let cleaner (thus faster and smaller) machine code be emitted
Looks like a compile-time assert is the only right thing. Is there any possible reason to prefer a run-time assert here?
assert
usually does not throw an exception but rather aborts the program. – SteelsBOOST_STATIC_ASSERT
is probably right out of the question. – Marcellemarcellina