This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of C++17 status.

### 2519. Iterator `operator-=` has gratuitous undefined behaviour

Section: 23.3.5.7 [random.access.iterators] Status: C++17 Submitter: Hubert Tong Opened: 2015-07-15 Last modified: 2017-07-30

Priority: 2

View all other issues in [random.access.iterators].

View all issues with C++17 status.

Discussion:

In subclause 23.3.5.7 [random.access.iterators], Table 110, the operational semantics for the expression "`r -= n`" are defined as

>     return r += -n;

Given a `difference_type` of a type `int` with range [-32768, 32767], if the value of `n` is -32768, then the evaluation of `-n` causes undefined behaviour (Clause 5 [expr] paragraph 4).

The operational semantics may be changed such that the undefined behaviour is avoided.

Suggested wording:

Replace the operational semantics for "`r -= n`" with:

>     {
>       difference_type m = n;
>       if (m >= 0)
>         while (m--)
>           --r;
>       else
>         while (m++)
>           ++r;
>       return r;
>     }

Jonathan Wakely:

I'm now convinced we don't want to change the definition of `-=` and instead we should explicitly state the (currently implicit) precondition that `n != numeric_limits<difference_type>::min()`.

[2016-08, Chicago]

Monday PM: Move to Tentatively Ready

Proposed resolution:

This wording is relative to N4527.

1. Change Table 110 "Random access iterator requirements (in addition to bidirectional iterator)" as indicated:

   > Table 110 — Random access iterator requirements (in addition to bidirectional iterator)
   > Expression | Return type | Operational semantics | Assertion/note pre-/post-condition
   > --- | --- | --- | ---
   > `…`
   > `r -= n` | `X&` | `return r += -n;` | pre: the absolute value of `n` is in the range of representable values of `difference_type`.
   > `…`