constexpr and reinterpret_cast: Error in C Compilation
Consider the following code snippet:
<br>struct foo {<br> static constexpr const void<em> ptr = reinterpret_cast<const void</em>>(0x1);<br>};<br>
This code compiles without errors in g v4.9, but fails in clang v3.4 with the error:
error: constexpr variable 'ptr' must be initialized by a constant expression
Which Compiler is Correct?
According to the C 11 standard, clang is correct. The standard states that a constant expression must not involve a reinterpret_cast. This means that the initialization of ptr in the code snippet is invalid.
Proper Initialization
The proper way to declare an expression of this type would be to use an alternative method, such as:
<br>struct foo {<br> static constexpr intptr_t ptr = 0x1;<br>};<br>
This would work in both clang and g .
Workaround for GCC
While GCC's acceptance of the original code snippet is technically incorrect, it does support a workaround using the __builtin_constant_p macro:
<br>struct foo {<br> static constexpr const void* ptr =</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">__builtin_constant_p( reinterpret_cast<const void*>(0x1) ) ? reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1);
};
This workaround allows GCC to fold the non-constant expression and treats it as a constant. However, it is not part of the C standard and should be used with caution.
The above is the detailed content of Why Does `reinterpret_cast` Cause a Compilation Error When Initializing a `constexpr` Variable?. For more information, please follow other related articles on the PHP Chinese website!