使用ssize_t供VS INT [英] Using ssize_t vs int
问题描述
我有,我可以在四个可能的方法的有一个的写一个函数:
I've got a function which I can write in one of the four possible ways:
int do_or_die(int retval);
int do_or_die(ssize_t retval);
ssize_t do_or_die(int t 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
问题
- 我应该使用哪种原型?
- 我应该给
写
和打印
? 哪些类型 - Which prototype should I use?
- What types should I give to
written
andprinted
? -
INT
可存储至少在区间[-2 ^ 15 ... 2 ^ 15-1]每ISO C 值 -
ssize_t供
可存储至少范围在[-1 ... 2 ^ 15-1]每POSIX(见<一值href=\"http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html\"><$c$c>_POSIX_SSIZE_MAX$c$c>). 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
我想拥有的最强大和最标准的code,同时还具有只有一个 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.
推荐答案
有在C或POSIX标准的sizeof(int)的&GT难保; = sizeof的(ssize_t供)
,也不周围的其他方法。通常 ssize_t供
比 INT
较大,但在C99安全和便携的选择是使用还会将intmax_t
来代替参数和返回值。
There's no guarantee in the C or POSIX standards 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供VS INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!