You can think of assertions as sanity checks. You know that some condition should be true unless you've screwed something up, so the assertion should pass. If you have indeed screwed something up, the assertion will fail and you'll be told that something is wrong. It's just there to ensure the validity of your code.
A static_assert
can be used when the condition is a constant expression. This basically means that the compiler is able to evaluate the assertion before the program ever actually runs. You will be alerted that a static_assert
has failed at compile-time, whereas a normal assert
will only fail at run time. In your example, you could have used a static_assert
, because the expressions 2+2==4
and 2+2==5
are both constant expressions.
static_assert
s are useful for checking compile-time constructs such as template parameters. For example, you could assert that a given template argument T
must be a POD type with something like:
static_assert(std::is_pod<T>::value, "T must be a POD type");
Note that you generally only want run-time assertions to be checked during debugging, so you can disable assert
by #define
ing NDEBUG
.