Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c - Using ssize_t vs int

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.

question from:https://stackoverflow.com/questions/19224655/using-ssize-t-vs-int

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...