In general, size_t
should be used whenever you are measuring the size of something. It is really strange that size_t
is only required to represent between 0 and SIZE_MAX
bytes and SIZE_MAX
is only required to be 65,535...
The other interesting constraints from the C++ and C Standards are:
- the return type of
sizeof()
is size_t
and it is an unsigned integer
operator new()
takes the number of bytes to allocate as a size_t
parameter
size_t
is defined in <cstddef>
SIZE_MAX
is defined in <limits.h>
in C99 but not mentioned in C++98?!
size_t
is not included in the list of fundamental integer types so I have always assumed that size_t
is a type alias for one of the fundamental types: char
, short int
, int
, and long int
.
If you are counting bytes, then you should definitely be using size_t
. If you are counting the number of elements, then you should probably use size_t
since this seems to be what C++ has been using. In any case, you don't want to use int
- at the very least use unsigned long
or unsigned long long
if you are using TR1. Or... even better... typedef
whatever you end up using to size_type
or just include <cstddef>
and use std::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.
Best Answer
From the friendly Wikipedia:
Also, check Why size_t matters