ptrdiff_t. A basic signed integer C/C++ type. The type's size is chosen so that it could store the maximum size of a theoretically possible array of any type. On a 32-bit system ptrdiff_t will take 32 bits and on a 64-bit one - 64 bits. In other words, a pointer can be safely put inside ptrdiff_t type (an exception is class-function-pointers but this is a special case). By the way the result of the expression where one pointer is subtracted from another (ptr1-ptr2) will have ptrdiff_t type. ptrdiff_t type is usually used for loop, array indexing, size storage and address arithmetic. ptrdiff_t type has its synonym intptr_t whose name indicates more clearly that it can store a pointer. In some cases using ptrdiff_t type is more effective and safe than using a more habitual for the programmer int type.

In the terms of static analyzer PVS-Studio, type ptrdiff_t refers to memsize-types. The analyzer includes Viva64 system for detailed error detection in 64-bit programs and for code optimization. Many diagnostic messages shown by Viva64 analyzer relate to recommendations on using memsize-types. Using memsize-types (such as size_t, ptrdiff_t, INT_PTR) instead of 32-bit types (int, unsigned) in 64-bit programs allows you to:

  • enable the compiler to build a simpler and therefore faster code which will have no unnecessary conversions of 32-bit and 64-bit data. It is especially useful when operating with address arithmetic and array indexing.
  • avoid some errors when processing a large size of input data when the number of the elements being processed excesses the number INT_MAX.
  • avoid some other more specific errors.
  • make the code more portable among 64-bit versions of Windows and Linux systems which use different data models. Thus, for example, in Linux systems you can use unsigned long type for indexing large arrays while in Windows it is impossible.

To learn more about the errors you can avoid when using ptrdiff_t type and also how this type allows improving and optimizing your 64-bit programs, see the articles given in the references.

If you are planning to start developing 64-bit projects or porting the existing 32-bit projects on 64-bit systems, we would like to offer you purchasing PVS-Studio analyzer which will simplify this task greatly and allow you to avoid the long period of searching hidden errors.


Bugs Found

Checked Projects
Collected Errors
14 526
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →