Checking Programming Errors at Compile Time
Learn how to check programming errors during compilation using assert and static_assert.
We'll cover the following
Assert statements are a simple but very powerful tool for validating invariants and contracts between callers and callees in a codebase. It’s possible to check programming errors while executing the program using assert()
. But we should always strive to detect errors as early as possible, and if we have a constant expression, we can catch programming errors when compiling the program using static_assert()
.
Using assert to trigger errors at runtime
Review the templated version of pow_n()
. We want to prevent it from being called with negative exponents (the n
value). To prevent this in the runtime version, where n
is a regular argument, we can add a runtime assertion:
Get hands-on with 1400+ tech skills courses.