C++11 nullptr and Pointer Arithmetic Explained

c++c++11nullptrpointers

Considering the following code, is it safe to do pointer arithmetic on nullptr?

I assume adding any offsets to a nullptr results in another nullptr, so far MSVC produce results as I expected, however I am a bit unsure about whether using nullptr like this is safe:

float * x = nullptr;

float * y = x + 31; // I assume y is a nullptr after this assigment

if (y != nullptr)
{
  /* do something */
}

Best Answer

You didn't define what "safe" means to you, but regardless, the code you propose has undefined behaviour. Pointer arithmetic is only allowed on pointer values that point into an array object, or perhaps to one-past-the-end of an array. (Non-array objects are considered an array of one element for the purpose of this rule.)

Since the null pointer is never the address of an object or one past an object, your code can never have well-defined behaviour.

Related Question