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
andprinted
?
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.
Use types in a way:
signed
andunsigned
types together andssize_t
might be an alias forint
, yet it is not standard C and might be environment specific.If your program will run in specific environment, check whether
sizeof(ssize_t) <= sizeof(int)
and useint
. Otherwise, use some other typeT
wheresizeof(T)
is greater or equal than bothsizeof(int)
andsizeof(ssize_t)
.There's no guarantee in the POSIX standard that
sizeof(int) >= sizeof(ssize_t)
, nor the other way around. Typicallyssize_t
is larger thanint
, but the safe and portable option in C99 is to useintmax_t
instead for the argument and the return value.The only guarantees you have wrt. the relationship between
int
andssize_t
are: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
).(Interestingly, there isn't even a guarantee that
ssize_t
can store the negative counterparts of its positive range. It's not a signedsize_t
, but a "size type" with an error value.)