Home >Backend Development >C++ >Can `reinterpret_cast` be used to initialize a `constexpr` static const void pointer?

Can `reinterpret_cast` be used to initialize a `constexpr` static const void pointer?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 03:19:101032browse

Can `reinterpret_cast` be used to initialize a `constexpr` static const void pointer?

constexpr and Initialization of a Static const Void Pointer with reinterpret cast: Compiler Discrepancy

The following code snippet illustrates the issue:

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

Compiler Discrepancy

While this code compiles successfully in g v4.9, it fails to compile in clang v3.4. Clang generates the error:

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

Standard Compliance

According to the C 11 standard, a constexpr variable must be initialized by a constant expression. Reinterpret_cast is not a constant expression, as stated in section 5.19 paragraph 2 of the draft C 11 standard. Therefore, clang is correct in rejecting the code.

Proper Declaration

The proper way to declare a constexpr variable with a reinterpret cast is to use the __builtin_constant_p macro. This macro allows constant folding of non-constant expressions. The following modified code compiles in both g and clang:

static constexpr const void* ptr = 
  __builtin_constant_p( reinterpret_cast<const void*>(0x1) ) ? 
    reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1)  ;

This code uses the ternary conditional operator to test if the reinterpret cast expression is a constant expression. If true, the cast is performed, otherwise the evaluation fails.

The above is the detailed content of Can `reinterpret_cast` be used to initialize a `constexpr` static const void pointer?. 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