13

I know that pointer arithmetic is disallowed for null pointers. But imagine I have something like this:

class MyArray {
  int *arrayBegin;  // pointer to the first array item, NULL for an empty array
  unsigned arraySize;   // size of the array, zero for an empty array
public:
  int *begin() const { return arrayBegin; }
  int *end() const { return arrayBegin + arraySize; }  // possible? (arrayBegin may be null)

Is it possible (allowed) to have the above end() implementation? Or is it necessary to have:

  int *end() const { return (arraySize == 0) ? nullptr : (arrayBegin + arraySize); }

to avoid pointer arithmetic with nullptr because arrayBegin is null for an empty array (despite arraySize also being zero in this case)?

I know it's possible to store int *end; instead of unsigned size; and let size be computed as end-begin - but then comes the same issue: Is it allowed to compute nullptr - nullptr?

I would especially appreciate standard references.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jarek C
  • 1,077
  • 6
  • 18

1 Answers1

14

Yes, you can add zero to the null pointer and subtract one null pointer from another. Quoting Additive operators [expr.add] section of the C++ standard:

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.

  • If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.
vitaut
  • 49,672
  • 25
  • 199
  • 336
Sergey Strukov
  • 373
  • 3
  • 9
  • 10
    What is "8.7 7"? If you refer to the C++ Standard, please, specify which one. Generally, it is better to use section "names" in brackets, since section/chapter/paragraph numbering generally changes with each Standard version. In the current draft, the relevant section is [expr.add] paragraphs [4.1](http://eel.is/c++draft/expr.add#4.1) and [5.1](http://eel.is/c++draft/expr.add#5.1). – Daniel Langr Dec 19 '19 at 11:58