Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 618
W.F. Avatar asked Jan 03 '17 20:01

W.F.


2 Answers

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.

like image 109
SergeyA Avatar answered Nov 06 '22 05:11

SergeyA


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)

like image 44
Oleg Bogdanov Avatar answered Nov 06 '22 05:11

Oleg Bogdanov