1

The code below does not compile neither in gcc nor in clang. Both complain that, the reinterpret_cast to int* is not a constexpr.

How can I work-around the problem? Note that I cannot modify the macro PORT, as it is defined in a 3-rd party library (avr).

#include <iostream>
#define PORT ((int *)(0x20))
constexpr int *p = PORT;  // does not compile

int main() {
    std::cout << (uintptr_t) p << "\n";
    return 0;
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Fabio
  • 2,105
  • 16
  • 26

1 Answers1

1

Put simply, if you cannot modify PORT you cannot specify PORT as constexpr.

A constexpr expression cannot contain reinterpret_cast. It is undefined behavior. Keep in mind that a c-style cast like (int*) is reduced to either static_cast or reinterpret_cast, in this case, reinterpret_cast.

Given your example, I don't see why you wouldn't just use const.

const int *p = PORT;
Cinder Biscuits
  • 4,880
  • 31
  • 51
  • Turns out I simplified too much my use case. I have accepted this, but posted a similar question here: https://stackoverflow.com/questions/54174694/reinterpret-castvolatile-uint8-t37-is-not-a-constant-expression – Fabio Jan 14 '19 at 01:07