C++ Standard Library C++ STL Library

C++ <cstddef> - ptrdiff_t Type



The C++ <cstddef> ptrdiff_t type is an alias of one of the fundamental signed integer type. This is a type able to represent the difference of two pointers.

ptrdiff_t is used for pointer arithmetic and array indexing. A pointer difference is only guaranteed to have a valid defined value for pointers to elements of the same array (or for past-the-last element of the same array).

In the <cstddef> header file, it is defined as follows:

typedef /* implementation-defined */ ptrdiff_t;              

Example:

The example below shows the usage of ptrdiff_t type.

#include <iostream>
#include <cstddef>
using namespace std;
 
int main (){
  //creating an array of size 10
  int N = 10;
  int* Arr = new int[N];
    
  //populating the elements of array
  //using ptrdiff_t type
  int* end = Arr + N;
  for(ptrdiff_t i = N; i > 0; i--)
    *(end - i) = i;

  //displaying the elements of array
  //using ptrdiff_t type
  cout<<"Arr contains: ";
  for(ptrdiff_t i = N; i > 0; i--)
    cout<<*(end - i)<<" ";
 
  return 0;
}

The output of the above code will be:

Arr contains: 10 9 8 7 6 5 4 3 2 1 

❮ C++ <cstddef> Library