40

Code

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

And then it will be called with both of these ways for library functions:

    written = do_or_die(write(...)); // POSIX write returns ssize_t
    printed = do_or_die(printf(...)); // printf returns int

Questions

  • Which prototype should I use?
  • What types should I give to written and printed?

I want to have the most robust and standard code, while still having just one do_or_die function.

I am using C99 in this case, but if answer is different for C11, then I'd like to know that too, for future.

4

3 回答 3

54

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.

The only guarantees you have wrt. the relationship between int and ssize_t are:

  • int can store values of at least the range [-2^15 ... 2^15-1] per ISO C
  • ssize_t can store values of at least the range [-1 ... 2^15-1] per POSIX (see _POSIX_SSIZE_MAX).

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

于 2013-10-07T12:22:19.900 回答
5

以某种方式使用类型:

  • 你不混合signedunsigned类型在一起
  • 您不会截断较大类型的值,同时将它们存储在较小的类型中(溢出/下溢)

ssize_t可能是 的别名int,但它不是标准 C 并且可能是特定于环境的。

如果您的程序将在特定环境中运行,请检查是否sizeof(ssize_t) <= sizeof(int)使用int. T否则,请使用sizeof(T)大于或等于两者的其他类型sizeof(int)sizeof(ssize_t)

于 2013-10-07T12:25:29.857 回答
1

您可以使用 int 或 long int 数据类型,但ssize_t它是一种系统数据类型,应该用于跨平台可移植性。基本类型(例如'int')在不同的实现上可以是不同的大小。通常发生的情况是系统类型(在这种情况下ssize_t)利用 C 的 typedef 特性,以便使用机器特定的数据类型大小,例如typedef signed ssize_t(这是 SUSv3 标准数据类型的一部分)。在实现任何类型的系统级编程时,尽可能使用系统数据类型是一种很好的做法。

有关更详细的描述,请参阅 Linux 编程接口 (Michael Kerrisk)

于 2020-09-13T00:29:08.223 回答