C/C++言語におけるヌルポインタ同士の減算に関するメモ。
int *p = NULL, *q = NULL; ptrdiff_t x = (p - q); // x == 0 ?
まとめ:
- C言語仕様上は未定義動作(undefined behavior)。とはいえ、大半の処理系では値0になると予測される(単に経験則)。
- 2024-12-12追記:次期仕様C2y向け提案文書(PDF)N3322が採択され*1、C++同様に
NULL-NULL == 0が保証される。記事 Making memcpy(NULL, NULL, 0) well-defined も参照のこと。
- 2024-12-12追記:次期仕様C2y向け提案文書(PDF)N3322が採択され*1、C++同様に
- 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_tdefined 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