Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

ptrdiff_t — pointer difference type

ptrdiff_t is the signed integer type for pointer subtraction. It measures distance in elements, not bytes.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stddef.h>
ptrdiff_t distance = end - begin;

ptrdiff_t from <stddef.h> is the result type of pointer subtraction. Unlike unsigned size_t, it can represent negative distances. Its size is implementation-defined.

Pointers must designate elements of the same array or its one-past position. For pointer subtraction, C treats an object that is not an array element as the sole element of an array of length one. Subtracting two pointers to that same object is therefore valid and yields zero. The result is the difference of indices. Subtracting pointers to unrelated objects, or obtaining a result unrepresentable in ptrdiff_t, causes undefined behavior.

Use %td for printing. The example uses a one-past pointer without dereferencing it.

Examples

#include <stddef.h>
#include <stdio.h>

int main(void)
{
    int a[5] = {0};
    ptrdiff_t forward = (a + 5) - (a + 1);
    ptrdiff_t backward = (a + 1) - (a + 5);
    printf("%td %td\n", forward, backward);
    return 0;
}

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