Home >Backend Development >C++ >Is reinterpret_cast of a Literal Valid for Initializing a constexpr Static Const Void Pointer?
Consider the following code snippet:
struct foo { static constexpr const void* ptr = reinterpret_cast<const void*>(0x1); }; auto main() -> int { return 0; }
This code compiles successfully in g v4.9 but fails in clang v3.4, generating the error:
error: constexpr variable 'ptr' must be initialized by a constant expression
According to the C 11 standard section 5.19 (Constant Expressions), conditional expressions are not considered core constant expressions when they involve reinterpret_cast. Therefore, clang is correct in flagging this code as an error.
A simple solution is to use intptr_t instead and cast to void* when needed:
static constexpr intptr_t ptr = 0x1; reinterpret_cast<void*>(foo::ptr);
However, gcc and clang support an undocumented workaround using __builtin_constant_p to allow constant folding of non-constant expressions:
static constexpr const void* ptr = __builtin_constant_p(reinterpret_cast<const void*>(0x1)) ? reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1);
The above is the detailed content of Is reinterpret_cast of a Literal Valid for Initializing a constexpr Static Const Void Pointer?. For more information, please follow other related articles on the PHP Chinese website!