constexpr and Initialization of a Static const void Pointer with reinterpret_cast: Compiler Differences Explained
In the given code snippet, a static constexpr const void pointer is declared using a reinterpret_cast. This code raises a question about which compiler interpretation is correct according to the standard and the proper way to declare such expressions.
Compiler Rightfulness
The standard dictates that a constexpr variable, such as the static const void pointer in this case, must be initialized with a constant expression. A reinterpret_cast expression, however, is not considered a core constant expression according to the C 11 standard. Therefore, clang is correct in reporting an error for this code.
Proper Declarations
To declare a static constexpr const void pointer correctly, there are a few options:
Use intptr_t instead: Use an intptr_t type and cast it to a void pointer when retrieving the value, as follows:
static constexpr intptr_t ptr = 0x1; // ... reinterpret_cast<void*>(ptr);
GCC/clang Extension: GCC and clang support a little-documented extension using __builtin_constant_p:
static constexpr const void* ptr = __builtin_constant_p( reinterpret_cast<const void*>(0x1) ) ? reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1) ;
This expression will be constant-folded by both compilers. However, note that this extension is not part of the standard and may not be supported in future versions of the compiler.
The above is the detailed content of Is it legal to initialize a static constexpr const void pointer using reinterpret_cast?. For more information, please follow other related articles on the PHP Chinese website!