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.