Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned int vs. size_t

Tags:

c++

c

size-t

I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.

like image 729
Rob Avatar asked Sep 25 '08 07:09

Rob


People also ask

Is it better to use Size_t or int?

When writing C code you should always use size_t whenever dealing with memory ranges. The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic.

Is Size_t unsigned or signed?

size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model. The bit width of size_t is not less than 16.

Why is Size_t unsigned?

size_t is unsigned because negative sizes make no sense.

Is Size_t guaranteed to be unsigned?

Yes, size_t is guaranteed to be an unsigned type.


1 Answers

The size_t type is the unsigned integer type that is the result of the sizeof operator (and the offsetof operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).

The size_t type may be bigger than, equal to, or smaller than an unsigned int, and your compiler might make assumptions about it for optimization.

You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.

like image 195
Remo.D Avatar answered Sep 17 '22 13:09

Remo.D