I know that static_assert
makes assertions at compile time, and assert
- at run time, but what is the difference in practice? As far as I understand, deep down they are pieces of code, like
if (condition == false) exit();
static_assert
will work, or only assert
?if
statement can't do?You ask three questions, so I will try to answer each of them.
static_assert
will work, or only assert
?static_assert
is good for testing logic in your code at compilation time. assert
is good for checking a case during run-time that you expect should always have one result, but perhaps could somehow produce an unexpected result under unanticipated circumstances. For example, you should only use assert
for determining if a pointer passed into a method is null
when it seems like that should never occur. static_assert
would not catch that.
if
statement can't do?assert
can be used to break program execution, so you could use an if
, an appropriate error message, and then halt program execution to get a similar effect, but assert
is a bit simpler for that case. static_assert
is of course only valid for compilation problem detection while an if
must be programmatically valid and can't evaluate the same expectations at compile-time. (An if
can be used to spit out an error message at run-time, however.)
Not at all!