Home > Backend Development > C++ > Is it legal to initialize a static constexpr const void pointer using reinterpret_cast?

Is it legal to initialize a static constexpr const void pointer using reinterpret_cast?

Linda Hamilton
Release: 2024-11-12 03:35:01
Original
960 people have browsed it

Is it legal to initialize a static constexpr const void pointer using reinterpret_cast?

constexpr and Initialization of a Static const void Pointer with reinterpret_cast: Compiler Differences Explained

In the given code snippet, a static constexpr const void pointer is declared using a reinterpret_cast. This code raises a question about which compiler interpretation is correct according to the standard and the proper way to declare such expressions.

Compiler Rightfulness

The standard dictates that a constexpr variable, such as the static const void pointer in this case, must be initialized with a constant expression. A reinterpret_cast expression, however, is not considered a core constant expression according to the C 11 standard. Therefore, clang is correct in reporting an error for this code.

Proper Declarations

To declare a static constexpr const void pointer correctly, there are a few options:

  1. Use intptr_t instead: Use an intptr_t type and cast it to a void pointer when retrieving the value, as follows:

    static constexpr intptr_t ptr = 0x1;
    // ...
    reinterpret_cast<void*>(ptr);
    Copy after login
  2. GCC/clang Extension: GCC and clang support a little-documented extension using __builtin_constant_p:

    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 will be constant-folded by both compilers. However, note that this extension is not part of the standard and may not be supported in future versions of the compiler.

The above is the detailed content of Is it legal to initialize a static constexpr const void pointer using reinterpret_cast?. 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