Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ptrdiff_t — pointer difference type

std::ptrdiff_t is an implementation-defined signed integer type from <cstddef>. It is the result type of pointer subtraction, representing a distance in elements rather than bytes, and can hold negative values.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <cstddef>
std::ptrdiff_t distance = last - first;

std::ptrdiff_t, available after including <cstddef>, is an alias for an implementation-selected signed integer type. Do not assume it is int or long, or that it has a fixed width. Built-in pointer subtraction produces a result of this type.

For pointers into the same array, last - first means the difference between their indices, not a byte count. A pointer one past the array's end may participate, but must not be dereferenced. Reversing the operands reverses the result's sign.

Subtracting pointers into separate arrays causes undefined behavior, even when their addresses are close together. A difference outside the representable range of std::ptrdiff_t also causes undefined behavior. Storing the result in a wider type does not repair the subtraction itself.

In contrast, std::size_t is unsigned and is used, among other things, for object sizes in bytes. Do not use it to store a potentially negative difference.

In the example, last points one past the four-element array, so last - first is 4 and first - last is -4. In the tested environment, the program prints those values as decimal numbers. On an implementation with sufficiently wide bytes, however, std::ptrdiff_t can be an alias for signed char. In that case, inserting the values directly into std::cout with << writes characters rather than decimal numbers.

Examples

#include <cstddef>
#include <iostream>

int main() {
    int values[] = {10, 20, 30, 40};
    const int* first = values;
    const int* last = values + 4;

    std::ptrdiff_t forward = last - first;
    std::ptrdiff_t backward = first - last;

    std::cout << forward << '\n' << backward << '\n';
}

Result

4
-4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources