Difference between size_t and std::size_t

后端 未结 3 1635
鱼传尺愫
鱼传尺愫 2020-12-07 12:36

What are the differences between size_t and std::size_t in terms of where they are declared, when they should be used and any other differentiating

相关标签:
3条回答
  • 2020-12-07 13:17

    std::size_t is in fact stddef.h's size_t.

    cstddef gives the following:

    #include <stddef.h>
    namespace std 
    {
      using ::ptrdiff_t;
      using ::size_t;
    }
    

    ...effectively bringing the previous definition into the std namespace.

    0 讨论(0)
  • 2020-12-07 13:27

    From C++03 "17.4.3.1.4 Types":

    For each type T from the Standard C library (footnote 169), the types ::T and std::T are reserved to the implementation and, when defined, ::T shall be identical to std::T.

    And footnote 169:

    These types are clock_t, div_t, FILE, fpos_t, lconv, ldiv_t, mbstate_t, ptrdiff_t, sig_atomic_t, size_t, time_t, tm, va_list, wctrans_t, wctype_t, and wint_t.

    0 讨论(0)
  • 2020-12-07 13:40

    C's size_t and C++'s std::size_t are both same.

    In C, it's defined in <stddef.h> and in C++, its defined in <cstddef> whose contents are the same as C header (see the quotation below). Its defined as unsigned integer type of the result of the sizeof operator.

    C Standard says in §17.7/2,

    size_t which is the unsigned integer type of the result of the sizeof operator

    And C++ Standard says (about cstddef header) in §18.1/3,

    The contents are the same as the Standard C library header , with the following changes.

    So yeah, both are same; the only difference is that C++ defines size_t in std namespace.

    Please also notice that the above line also says "with the following changes" which isn't referring to size_t. Its rather referring to the new additions (mostly) made by C++ into the language (not present in C) which are also defined in the same header.


    Wikipedia has very good info about range and storage size of size_t:

    Range and storage size of size_t

    The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors,[3][4] when moving from 32 to 64-bit architecture, for example.

    According to the 1999 ISO C standard (C99), size_t is an unsigned integer type of at least 16 bits.

    And the rest you can read from this page at wikipedia.

    0 讨论(0)
提交回复
热议问题