Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GCC have a built-in compile time assert?

Our existing compile-time assert implementation is based on negative array index, and it provides poor diagnostic output on GCC. C++0x's static_assert is a very nice feature, and the diagnostic output it provides is much better. I know GCC has already implemented some C++0x features. Does anyone know if static_assert is among them and if it is then since what GCC version?

like image 356
VladLosev Avatar asked Jun 12 '09 16:06

VladLosev


People also ask

Is assert compile time?

assert(f != must be done at run time. However, an assertion that tests the value of a constant expression, such as the size or offset of a structure member, can be done at compile time.

Does C have Static_assert?

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.

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 .

What is Static_assert?

What is static assertion? 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. Performs compile-time assertion checking.


2 Answers

According to this page, gcc has had static_assert since 4.3.

like image 167
Evan Teran Avatar answered Sep 28 '22 09:09

Evan Teran


If you need to use a GCC version which does not support static_assert you can use:

#include <boost/static_assert.hpp>

BOOST_STATIC_ASSERT( /* assertion */ )

Basically, what boost does is this:

Declare (but don't define!) a

template< bool Condition > struct STATIC_ASSERTION_FAILURE;

Define a specialization for the case that the assertion holds:

template <> struct STATIC_ASSERTION_FAILURE< true > {};

Then you can define STATIC_ASSERT like this:

#define STATIC_ASSERT(Condition) \ 
  enum { dummy = sizeof(STATIC_ASSERTION_FAILURE< (bool)(Condition) > ) }

The trick is that if Condition is false the compiler needs to instantiate the struct

STATIC_ASSERTION_FAILURE< false >

in order to compute its size, and this fails since it is not defined.

like image 32
Tobias Avatar answered Sep 28 '22 08:09

Tobias