6

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;
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137
W.F.
  • 13,888
  • 2
  • 34
  • 81

2 Answers2

14

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.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Or two null pointers IIRC, which is also certainly not the case. –  Jan 03 '17 at 20:43
  • 1
    So I over-interpreted the wording? Yep I tested it too but I learnt that the fact something isn't compiling in given compiler doesn't really meen it actually is not legal hence the question :) – W.F. Jan 03 '17 at 20:44
  • @hvd, i do not remember any exception for null pointers regarding the subtraction, but my memory may fail me. Would you be so kind to provide a quote? – SergeyA Jan 03 '17 at 20:45
  • @W.F., while compilers, may, indeed, have bugs, when several compilers agree on something, it's a strong hint that you are the one which got it wrong :-P – SergeyA Jan 03 '17 at 20:46
  • @SergeyA http://stackoverflow.com/questions/8128168/is-the-behavior-of-subtracting-two-null-pointers-defined is easier to find for me than the quote in the standard :) –  Jan 03 '17 at 20:46
  • @SergeyA I agree, however this is c++17 theoretically not yet supported fully by the compilers ;) :-P – W.F. Jan 03 '17 at 20:47
  • @SergeyA Thank you for the response! I'll give a little bit more time to possible other suggestions and if nothing shows up I'll accept your answer. – W.F. Jan 03 '17 at 20:55
  • 1
    @W.F. this was post-c++14 DR [1313](http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1313) (now noted at the bottom of that cppreference page) – Cubbi Jan 03 '17 at 23:39
3

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)

Oleg Bogdanov
  • 1,712
  • 13
  • 19