Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between assert and static_assert?

Tags:

c++

assert

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?
like image 731
Oleksiy Avatar asked Aug 13 '13 13:08

Oleksiy


People also ask

Where is static_assert defined?

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.

What is static_assert C++?

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.

When should I use assert?

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.

Is static assert compile time?

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 .


1 Answers

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!

like image 179
pattivacek Avatar answered Oct 07 '22 12:10

pattivacek