Title
Accidental removal of undefined behavior in pointer subtraction
Status
open
Section
7.6.6 [expr.add]
Submitter
Jan Schultke

Created on 2026-06-13.00:00:00 last changed 1 week ago

Messages

Date: 2026-09-20.15:50:16

Possible resolution:

  1. Change in 7.6.6 [expr.add] paragraph 5 as follows:

    The result of subtracting two pointer expressions P and Q is a prvalue of type std::ptrdiff_t (17.2.4 [support.types.layout]).
    • If P and Q both evaluate to null pointer values, the value is 0.
    • Otherwise, if P and Q point to, respectively, array elements i and j of the same array object x, the expression P - Q has the value i - j. [Note 2: If ; if the that value i - j is not in the range of representable values of type std::ptrdiff_t, the behavior is undefined (7.1 [expr.pre] [expr.sub.pointers.rep]). —end note]
    • Otherwise, the behavior is undefined (F.3.31 [ub:expr.add.sub.diff.pointers]).
  2. Add a subclause before F.3.31 [ub:expr.add.sub.diff.pointers] as follows:

    [ub:expr.sub.pointers.rep]
    Specified in: 7.6.6 [expr.add]
    Subtracting two expressions of pointer type where the difference is not representable in std::ptrdiff_t is undefined behavior. [Example:
      char big[static_cast<std::uintmax_t>(PTRDIFF_MAX) + 1];
      std::ptrdiff_t d = (big + sizeof(big) - big);   // undefined behavior
    
    —end example]
Date: 2026-06-13.00:00:00

(From submission #922.)

Paper P3899R3 (Clarify the behavior of floating-point overflow), adopted in June, 2026, accidentally removed undefined behavior for the case where the result of subtracting two pointer values is not representable as a std::ptrdiff_t. Undefined behavior was limited to arithmetic expressions, which pointer subtraction is not.

History
Date User Action Args
2026-09-20 14:52:08adminsetmessages: + msg8685
2026-06-13 00:00:00admincreate