Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::ptrdiff_t

      From cppreference.com
      <cpp‎ |types
       
       
      Utilities library
       
       
      Defined in header<cstddef>
      typedef/*implementation-defined*/ ptrdiff_t;

      std::ptrdiff_t is the signed integer type of the result of subtracting two pointers.

      The bit width ofstd::ptrdiff_t is not less than 17.

      (since C++11)

      Contents

      [edit]Notes

      std::ptrdiff_t is used forpointer arithmetic and array indexing, if negative values are possible. Programs that use other types, such asint, may fail on, e.g. 64-bit systems when the index exceedsINT_MAX or if it relies on 32-bit modular arithmetic.

      When working with the C++ container library, the proper type for the difference between iterators is the member typedefdifference_type, which is often synonymous withstd::ptrdiff_t.

      Only pointers to elements of the same array (including the pointer one past the end of the array) may be subtracted from each other.

      If an array is so large (greater thanPTRDIFF_MAX elements, but less thanSIZE_MAX bytes), that the difference between two pointers may not be representable asstd::ptrdiff_t, the result of subtracting two such pointers is undefined.

      For char arrays shorter thanPTRDIFF_MAX,std::ptrdiff_t acts as the signed counterpart ofstd::size_t: it can store the size of the array of any type and is, on most platforms, synonymous withstd::intptr_t.

      It is unspecified whether the declaration ofstd::ptrdiff_t is available in any other standard library header. An implementation may avoid introducing this name even when the standard requiresstd::ptrdiff_t to be used.

      [edit]Possible implementation

      // valid since C++11using ptrdiff_t= decltype(static_cast<int*>(nullptr)-static_cast<int*>(nullptr));

      [edit]Example

      Run this code
      #include <cstddef>#include <iostream> int main(){conststd::size_t N=10;int* a= newint[N];int* end= a+ N;for(std::ptrdiff_t i= N; i>0;--i)std::cout<<(*(end- i)= i)<<' ';std::cout<<'\n';    delete[] a;}

      Output:

      10 9 8 7 6 5 4 3 2 1

      [edit]See also

      unsigned integer type returned by thesizeof operator
      (typedef)[edit]
      byte offset from the beginning of astandard-layout type to specified member
      (function macro)[edit]
      C documentation forptrdiff_t
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/types/ptrdiff_t&oldid=173340"

      [8]ページ先頭

      ©2009-2025 Movatter.jp