Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-13 07:14:02
Original
455 people have browsed it

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);
};
Copy after login

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
Copy after login

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;
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template