Home >Backend Development >C++ >Is reinterpret_cast of a Literal Valid for Initializing a constexpr Static Const Void Pointer?

Is reinterpret_cast of a Literal Valid for Initializing a constexpr Static Const Void Pointer?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 03:32:02846browse

Is reinterpret_cast of a Literal Valid for Initializing a constexpr Static Const Void Pointer?

constexpr and Initialization of a Static Const Void Pointer with reinterpret cast: Which Compiler is Correct?

Problem Description

Consider the following code snippet:

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

auto main() -> int {
  return 0;
}

This code compiles successfully in g v4.9 but fails in clang v3.4, generating the error:

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

Questions

  1. Which compiler is correct according to the standard?
  2. What is the proper way to declare such an expression?

Answer

  1. clang Compiler is Correct

According to the C 11 standard section 5.19 (Constant Expressions), conditional expressions are not considered core constant expressions when they involve reinterpret_cast. Therefore, clang is correct in flagging this code as an error.

  1. Proper Declaration

A simple solution is to use intptr_t instead and cast to void* when needed:

static constexpr intptr_t ptr = 0x1;
reinterpret_cast<void*>(foo::ptr);

However, gcc and clang support an undocumented workaround using __builtin_constant_p to allow constant folding of non-constant expressions:

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

The above is the detailed content of Is reinterpret_cast of a Literal Valid for Initializing 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