以下の内容はhttps://yohhoy.hatenadiary.jp/entry/20120823/p1より取得しました。


NULL-NULL=?

C/C++言語におけるヌルポインタ同士の減算に関するメモ。

int *p = NULL, *q = NULL;
ptrdiff_t x = (p - q);  // x == 0 ?

まとめ

  • C言語仕様上は未定義動作(undefined behavior)。とはいえ、大半の処理系では値0になると予測される(単に経験則)。
  • C++言語仕様ではwell-defined。演算結果はstd::ptrdiff_t型の値0。

C

C99(JTC1/SC22/WG14 N1256) 6.5.6/p9より一部引用。C11(N1570)でも変更無し。

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. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined. (snip)

C++

C++03 5.7/p7より一部引用(下線部は強調)。C++11(JTC1/SC22/WG21 N3337)にも同一条項が存在する。

(snip) If two pointers point to the same object or both point one past the end of the same array or both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t.

関連URL




以上の内容はhttps://yohhoy.hatenadiary.jp/entry/20120823/p1より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14