What is the difference between assert and static_assert?

Oleksiy picture Oleksiy · Aug 13, 2013 · Viewed 16.8k times · Source

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();
  • Can someone give me an example of where only static_assert will work, or only assert?
  • Do they do anything a simple if statement can't do?
  • Is it bad practice to use them?

Answer

pattivacek picture pattivacek · Aug 13, 2013

You ask three questions, so I will try to answer each of them.

  • Can someone give me an example of where only 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.

  • Do they do anything a simple 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.)

  • Is it bad practice to use them?

Not at all!