ptrdiff_t is a special signed integer type defined in the standard library of C and C++ languages. It is a type of pointer subtraction result. The behavior of the type is similar to size_t: on a 32-bit system, the size of ptrdiff_t will be 32 bits, on a 64-bit system – 64 bits.
Also, when working with standard library containers, the result of subtracting two iterators has the difference_type type of the container being used, which, depending on the standard library, is often equal to ptrdiff_t.
The ptrdiff_t type is often used for address arithmetic and array indexing if negative values are possible. Programs that use regular integer types for this purpose may encounter undefined behaviour. For example, if the index value exceeds INT_MAX.
For arrays smaller than PTRDIFF_MAX, ptrdiff_t behaves like an analog of size_t: it can store the size of an array of any type and is synonymous with intptr_t on most platforms. However, if the array is large enough (larger than PTRDIFF_MAX, but smaller than SIZE_MAX) and the difference of its pointers cannot be represented as ptrdiff_t, the result of subtracting such pointers is undefined.
In C, the ptrdiff_t type is declared in the <stddef.h> header file. In C++, its declaration is located in <cstddef> and is placed in the global namespace and in std. Standard header files of the C language for backward compatibility can also be included in C++ programs.
In terminology of the PVS-Studio static analyzer, the ptrdiff_t type refers to memsize types. The analyzer has a large number of special 64-bit diagnostic rules issued by the analyzer and related specifically to the recommendation of implementing memsize types. If you are planning to start developing cross-platform projects or porting existing 32-bit projects to 64-bit systems, you may use PVS-Studio analyzer which can simplify this task greatly and allow you to avoid the long stage of searching for hidden errors.
To learn more about the errors you can avoid when using ptrdiff_t type and also how this type allows improving and optimizing your programs, see the articles given in the references.
0