should use size_t or ssize_t

C++UnsignedSignedSize T

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhgyxbllView Question on Stackoverflow
Solution 1 - C++madityaView Answer on Stackoverflow
Solution 2 - C++user657267View Answer on Stackoverflow