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?static_assert is a keyword defined in the <assert. h> header. It is available in the C11 version of C. static_assert is used to ensure that a condition is true when the code is compiled.
Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression.
assert() macro is used to test the conditions or assumptions that should not occur in a program. For example, the array index should always be > 0. Another assumption can be 2+2 == 3+1. So using assert () we can test such assumptions and as long as they evaluate to true, our program runs normally.
Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert .
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!
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