Home  >  Article  >  Backend Development  >  Can `reinterpret_cast` be used to initialize a `constexpr` variable?

Can `reinterpret_cast` be used to initialize a `constexpr` variable?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 07:14:02454browse

Can `reinterpret_cast` be used to initialize a `constexpr` variable?

constexpr Variable Initialization with reinterpret_cast and Compiler Compatibility

Consider the following code snippet:

struct foo {
  static constexpr const void* ptr = reinterpret_cast<const void*>(0x1);
};

When compiled with g v4.9, this code compiles successfully. However, clang v3.4 fails to compile, issuing the error:

error: constexpr variable 'ptr' must be initialized by a constant expression

Compiler Correctness

According to the C 11 draft standard (section 5.19, paragraph 2), a conditional-expression is not considered a constant expression if it involves a reinterpret_cast. Therefore, clang is correct in its interpretation that the initialization of ptr is not valid.

Proper Declaration

To properly declare a constant expression of this nature, one should use intptr_t instead and cast when necessary:

static constexpr intptr_t ptr = 0x1;

Alternatively, a workaround supported by both gcc and clang involves using the undocumented __builtin_constant_p macro:

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 is accepted by both compilers due to the __builtin_constant_p check, which forces the expression to be constant-folded.

The above is the detailed content of Can `reinterpret_cast` be used to initialize a `constexpr` variable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn