Discarded Function Values (To Cast or Not to Cast)
Rahul Dhesi
dhesi%cirrusl at oliveb.ATC.olivetti.com
Tue Nov 28 11:20:19 AEST 1989
In article <316 at voa3.UUCP> ck at voa3.UUCP (Chris Kern) writes:
>But what about a standard library function whose value I
>(perhaps recklessly) wish to ignore? Should I cast the function
>call to void, or am I just indulging in the trivial luxury of
>silencing lint?
I will crudely divide standard library functions into two groups, based
on their return value:
1. Those that return a status value
2. Those that return data
Many though not all of the standard I/O functions are in the first
category. Most of the string functions are in the second category.
(There are some that return one or the other, e.g., returning either
data or EOF. Handle with care.)
The return value from category 2 functions can usually be safely cast
to void. This is quite common with strcpy, strcat, and similar
functions that return a pointer whose value you already have
elsewhere. You are mainly accommodating the fact that what you needed
was a procedure but all you had was a function, and telling lint not to
remind you of this.
The return value from category 1 functions should be cast to void only
when you don't need the status value. This takes more thought than
with category 2 functions. Possibilities are:
a. You were reading from or writing to an I/O stream, and you will
check for an error later (e.g. with ferror). Most commonly you will do
a series of reads or writes without checking for an error each time,
and then finally test with ferror.
b. There isn't much you can do about the error now, so you just give
up. Very few people, for example, bother to check for an error
occurring on stderr after they have used fprintf to print an error
message to it.
c. You *know* what the status code is going to be, so you don't check
it. This usually arises out of careful analysis of your program, or
total recklessness. In either case, be very suspicious. I can't think
of many standard library functions that return a predictable status
code.
d. Anything else that I missed.
Rahul Dhesi <dhesi%cirrusl at oliveb.ATC.olivetti.com>
UUCP: oliveb!cirrusl!dhesi
More information about the Comp.lang.c
mailing list