使用 ssize_t 与 int [英] Using ssize_t vs int
问题描述
我有一个函数,我可以用 一种 四种可能的方式编写它:
I've got a function which I can write in one of four possible ways:
int do_or_die(int retval);
int do_or_die(ssize_t retval);
ssize_t do_or_die(int retval);
ssize_t do_or_die(ssize_t retval);
<小时>
然后它会被两种库函数调用:
written = do_or_die(write(...)); // POSIX write returns ssize_t
printed = do_or_die(printf(...)); // printf returns int
问题
- 我应该使用哪个原型?
- 我应该给
written
和printed
哪些类型? - Which prototype should I use?
- What types should I give to
written
andprinted
? int
可以根据 ISO C 存储至少 [-2^15 ... 2^15-1] 范围内的值ssize_t
可以根据 POSIX 存储至少 [-1 ... 2^15-1] 范围内的值(参见_POSIX_SSIZE_MAX
).int
can store values of at least the range [-2^15 ... 2^15-1] per ISO Cssize_t
can store values of at least the range [-1 ... 2^15-1] per POSIX (see_POSIX_SSIZE_MAX
).
Questions
我希望拥有最强大和最标准的代码,同时仍然只有一个 do_or_die
函数.
I want to have the most robust and standard code, while still having just one do_or_die
function.
在这种情况下我使用的是 C99,但如果 C11 的答案不同,那么我也想知道这一点,以备将来使用.
I am using C99 in this case, but if answer is different for C11, then I'd like to know that too, for future.
推荐答案
POSIX 标准不保证 sizeof(int) >= sizeof(ssize_t)
,反之亦然.通常 ssize_t
大于 int
,但 C99 中安全且可移植的选项是使用 intmax_t
代替参数和返回值.
There's no guarantee in the POSIX standard that sizeof(int) >= sizeof(ssize_t)
, nor the other way around. Typically ssize_t
is larger than int
, but the safe and portable option in C99 is to use intmax_t
instead for the argument and the return value.
您拥有 wrt 的唯一保证.int
和 ssize_t
的关系是:
The only guarantees you have wrt. the relationship between int
and ssize_t
are:
(有趣的是,甚至不能保证 ssize_t
可以存储其正数范围的负数.它不是带符号的 size_t
,而是大小类型"" 带有错误值.)
(Interestingly, there isn't even a guarantee that ssize_t
can store the negative counterparts of its positive range. It's not a signed size_t
, but a "size type" with an error value.)
这篇关于使用 ssize_t 与 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!