Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between size_t and std::size_t

Tags:

c++

size-t

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.


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.


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.