is size_t always unsigned?
Yes. It's usually defined as something like the following (on 32-bit systems):
typedef unsigned int size_t;
Reference:
C++ Standard Section 18.1 defines size_t
is in <cstddef>
which is described in C Standard as <stddef.h>
.
C Standard Section 4.1.5 defines size_t
as an unsigned integral type of the result of the sizeof
operator
According to the 1999 ISO C standard (C99), size_t
is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3).
The standard also recommends that size_t
shouldn't have an integer conversion rank greater than long
if possible, ie casting size_t
to unsigned long
is unproblematic if the recommendation is followed.
The 1989 ANSI C standard (ANSI C) doesn't mention a minimal size or recommended conversion rank.
The 1998 ISO C++ standard (C++98) (as well as the current draft for C++0x) refers to the C standard. Section 18.1 reads:
The contents are the same as the Standard C library header
<stddef.h>
[...]
According to section 1.2, this means the library as defined by the 1990 ISO C standard (C90), including its first amendment from 1995 (C95):
The library described in clause 7 of ISO/IEC 9899:1990 and clause 7 of ISO/IEC 9899/Amd.1:1995 is hereinafter called the Standard C Library.
The parts regarding size_t
should be inherited from ANSI C: Frontmatter and section numbering aside, the standards for C90 and ANSI C are identical. I'd need a copy of the normative amendment to be sure that there weren't any relevant changes to stddef.h
, but I doubt it. The minimal size seems to be introduced with stdint.h
, ie C99.
Please also consider the following quote from section 1.2 of C++98:
All standards are subject to revision, and parties to agreements based on this International Standard are encouraged to investigate the possibility of applying the most recent editions of the standards indicated below.
Yes, size_t is guaranteed to be an unsigned type.