Is difference between two pointers legal c++17 constant expression?

508 views Asked by At

According to cppreference section Core constant expressions point 19) a subtraction operator between two pointers is not legal constant expression until c++14. Can I assume that following code is legal c++17 code or is this interpretation an abuse?

int X, Y;

template <long long V>
struct S { };

int main() {
    S<&X - &Y> s;
    (void)s;
}
2

There are 2 answers

8
SergeyA On BEST ANSWER

The question is moot. Pointer arithmetics is only defined on the pointers belonging to the same array, which is certainly not the case there. So, the code above is not legal C++, and in fact, fails to compile with compilers available to me.

0
Oleg Bogdanov On

The quoted cppref article says

A core constant expression is any expression that does not have any one of the following ..

7) An expression whose evaluation leads to any form of core language (since C++17) undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc). Whether standard library undefined behavior is detected is unspecified. (since C++17)

19) a subtraction operator between two pointers(until C++14)

Likely only array ptr arithemtics inside array bounds is getting 'legalized' since c++14, not all pointer arithmetics


Actually a demo shows that array ptr arithmetics compiles alright even with c++11 (not c++98)