Constexpr pointer value

As Luc Danton notes, your attempts are blocked by the rules in [expr.const]/2 which say that various expressions are not allowed in core constant expressions, including:

— a reinterpret_cast
— an operation that would have undefined behavior [Note: including […] certain pointer arithmetic […] — end note]

The first bullet rules out your first example. The second example is ruled out by the first bullet above, plus the rule from [expr.cast]/4 that:

The conversions performed by […] a reinterpret_cast […] can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply.

The second bullet was added by WG21 core issue 1313, and clarifies that pointer arithmetic on a null pointer is not permitted in a constant expression. This rules out your third example.

Even if these restrictions did not apply to core constant expressions, it would still not be possible to initialize a constexpr pointer with a value produced by casting an integer, since a constexpr pointer variable must be initialized by an address constant expression, which, by [expr.const]/3, must evaluate to

the address of an object with static storage duration, the address of a function, or a null pointer value.

An integer cast to pointer type is none of these.

g++ does not yet strictly enforce these rules, but its recent releases have been getting closer to them, so we should assume that it will eventually fully implement them.

If your goal is to declare a variable for which static initialization is performed, you can simply drop the constexpr — both clang and g++ will emit a static initializer for this expression. If you need this expression to be part of a constant expression for some reason, you have two choices:

  • Restructure your code so that an intptr_t is passed around instead of a pointer, and cast it to pointer type when you need to (outside of a constant expression), or
  • Use __builtin_constant_p((int*)0xFF) ? (int*)0xFF : (int*)0xFF. This exact form of expression (with __builtin_constant_p on the left-hand-side of a conditional operator) disables strict constant expression checking in the arms of the conditional operator, and is a little-known, but documented, non-portable GNU extension supported by both gcc and clang.

Leave a Comment