2

Consider following code:

#include <iostream>

int main()
{
    int *a = 0, *b = 0;
    std::cout << (a - b);
}

At ideone this code prints 0 as expected, but I'm not sure if it is well-defined behavior or not.

I wonder if (T*)0 - (T*)0 is well-defined or not? Is it guaranteed to be equal to 0?
Is it same in C and C++? If not, what are the differences?

(Of course, T is not void nor std::nullptr_t, because pointer arithmetic does not work for them.)

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • The older question is explicitly limited to old versions of C and C++. This question was attracting answers for more modern versions, so I'm voting to reopen. – Adrian McCarthy Apr 09 '16 at 13:55
  • 2
    @AdrianMcCarthy Not sure I follow. While it was tagged with older versions in addition to the generic c++ / c tags, the top voted answer cites what looks like the same source as the only answer to this question for the C++03 and C++11 versions of the standard – Foon Apr 09 '16 at 14:34

1 Answers1

7

In C++, see [expr.add]/7:

If two pointers […] both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t.

(This also holds with P0137, which shortens this paragraph.)

In C11, the behavior is apparently undefined as per 6.5.6/9:

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

Columbo
  • 60,038
  • 8
  • 155
  • 203