At my code, I do not use int or unsigned int. I only use size_t or ssize_t for portable. For example:
typedef size_t intc; // (instead of unsigned int) typedef ssize_t uintc; // (instead of int)
Because strlen
, string
, vector
... all use size_t
, so I usually use size_t
. And I only use ssize_t
when it may be negative.
But I find that:
The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.
in the book The C++ Programming Language.
So I am puzzled. Am I wrong? Why does the STL not abide by the suggest on the book?
size_t is an unsigned integral type, that can represent the largest integer on you system. Only use it if you need very large arrays,matrices etc. Some functions return an size_t and your compiler will warn you if you try to do comparisons.
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.
Using size_t appropriately can improve the portability, efficiency, or readability of your code. Maybe even all three. Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes.
One standard recommendation is that the size_t be at most as big as an unsigned long. So you may think that we can use unsigned long in the place of size_t, but unsigned long on 64-bit system, if the OS ins Windows, will be of 32-bits, but size_t will be of 64-bits.
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With