应该使用size_t或ssize_t [英] should use size_t or ssize_t
问题描述
在我的代码中,我不使用int或unsigned int.我只将size_t或ssize_t用于便携式.例如:
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)
因为strlen
,string
,vector
...都使用size_t
,所以我通常使用size_t
.而且我只会在ssize_t
为负数时使用它.
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.
但是我发现:
无符号整数类型是将存储视为位数组的理想选择. 用一个无符号而不是一个整数来获得更多的比特来表示正整数几乎不是一个好主意. 通过声明无符号变量来确保某些值是正值的尝试通常会被隐式转换规则所破坏.
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.
在 C ++编程语言中进行.
所以我很困惑.我错了吗?为什么STL不遵守书中的建议?
So I am puzzled. Am I wrong? Why does the STL not abide by the suggest on the book?
推荐答案
ssize_t
用于其返回值可以是有效大小,也可以是负值以指示错误的函数.
保证能够存储至少在[-1, SSIZE_MAX]
范围内的值(SSIZE_MAX
与系统有关).
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).
因此,每当要返回以字节为单位的大小时,都应使用size_t
;每当要返回以字节为单位的大小或错误值(负)时,应使用ssize_t
.
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.
请参阅: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes .h.html
这篇关于应该使用size_t或ssize_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!