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:
Looks like a compile-time assert is the only right thing. Is there any possible reason to prefer a run-time assert here?
There's no reason to prefer a run-time assert here. You should prefer compile-time errors over run-time errors so there's never a reason, given the option between the two, to choose a run-time assert.
However, if a static assert isn't an option (doesn't know the concept of a static assert, doesn't know how to make one and doesn't have one available, or knows how to make one but doesn't have the time to), a run-time assert is the next best thing.
With C++0x, the built-in static_assert
feature should end all reason to use a run-time assert where a compile-time assert would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With