1

In C++ how can I get the integral representation of a pointer at compile time?

#include <bit>

constexpr int x = 5;
constexpr auto y = &x;

int main() {

    // The following does not work since it is forbidden for pointers!
    constexpr auto i = std::bit_cast<uintptr_t>(y);

    return 0;
}

Is there any hack to achieve this in C++20?

Any hidden compiler intrinsic or __builtin function?

I'm targetting Clang, GCC and MSVC.

João Pires
  • 927
  • 1
  • 5
  • 16
  • Possible duplicate. You have to refer to static usage, see: https://stackoverflow.com/questions/13499658/constexpr-initializing-with-pointers – Secundi Feb 03 '21 at 12:11
  • Does this answer your question? [constexpr initializing with pointers](https://stackoverflow.com/questions/13499658/constexpr-initializing-with-pointers) – Richard Critten Feb 03 '21 at 12:16
  • Because of [ASLR](https://en.wikipedia.org/wiki/Address_space_layout_randomization) that address (`&x`) is usually not a compile time constant. Some [relocation](https://en.wikipedia.org/wiki/Relocation_(computing)) could happen at dynamic-loading time (in [crt0](https://en.wikipedia.org/wiki/Crt0)...) at least on Linux – Basile Starynkevitch Feb 03 '21 at 12:17
  • I'm not trying to initialize a pointer at compile time, I'm trying to get its integral representation at compile time. – João Pires Feb 03 '21 at 12:37
  • From run to run, due to ASLR and other things, your pointer can have different values. Knowing this, do you think it’s possible that there is a single known vale of the pointer that can be known at compile time? – Mike Vine Feb 03 '21 at 12:46
  • I don't mind if the value is different every time the program runs, I really just want a constexpr integral value that can uniquely identify a pointer. – João Pires Feb 03 '21 at 13:01
  • 4
    You are using `std::bit_cast` to get the __value__ (in bits) of `y` which can't have a value until runtime. You can't get a compile time value of something that can only have a value a runtime. – Richard Critten Feb 03 '21 at 13:08
  • @JoãoPires, no, what you want to achieve in general is contradictory. The value must be known at compile time. If external linkage is forced for the variable, its definition must be unique for all occurrences further more. – Secundi Feb 03 '21 at 13:20
  • *I'm not trying to initialize a pointer at compile time,...* `constexpr auto y = &x;` is trying to initialize a pointer at compile time. *...I'm trying to get its integral representation at compile time* `y` has no integral representation at compile time, since it only has an integral representation at run time. `constexpr` is not magic. – Eljay Feb 03 '21 at 15:35

0 Answers0