Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid static assert behavior

I am trying to setup a static assert (outside the main function) with GCC v4.3.x:

#define STATIC_ASSERT(cond) extern void static_assert(int arg[(cond) ? 1 : -1])
STATIC_ASSERT( (double)1 == (double)1 ); // failed

but when I use float numbers, the assert always failed.

Is it possible to run this static assert properly ?

like image 297
Franck Freiburger Avatar asked Nov 22 '25 04:11

Franck Freiburger


2 Answers

C++ Standard 2003, 5.19 "Constant expressions", paragraph 1.

In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).

constant-expression: conditional-expression

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type tem- plate parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumeration types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.

like image 109
Alexey Malistov Avatar answered Nov 23 '25 21:11

Alexey Malistov


I think this has to do with the rule that a cast to anything but an integer or enumeration type can not appear in a constant expression.

// would all work for example
STATIC_ASSERT( 1.0 == 1.0 );
STATIC_ASSERT( (int)1.0 == (int)1.0 );

So it's not the assert itself that's invalid, and causes a compiler error, it's your cast...

Just for the record, boost, of course, has a static assert too.

like image 41
Pieter Avatar answered Nov 23 '25 20:11

Pieter