Why use (void) func() ?
Richard A. O'Keefe
ok at goanna.cs.rmit.oz.au
Tue Sep 25 14:10:22 AEST 1990
In article <586 at dptechno.UUCP>, dave at dptechno.uucp (Dave Lee)
[claims that he never accidentally omits to check the result of a
function, and asks why lint complains about it. He specifically
cites printf().]
> Why should I go to the extra trouble to write
> (void) printf("hello world\n");
> Instead of
> printf("hello world\n");
Stop and think for a moment. Why might lint have been made to check
for this in the first place? The answer is simple: the result that
you are ignoring is the only error indication you are going to get,
and ignoring it _may_ be very silly. I am sick of UNIX programs whose
authors KNEW that they could safely ignore the result of (say) write(),
with the result that I have lost valuable files because write errors
were ignored. (It's no good relying on a source management system to
protect your old versions when the source management system itself is
capable of storing large blocks of 0s for this very reason.)
printf() used to return 0 for success, -ve for failure.
In ANSI C, printf() returns #characters written for success, -ve for
failure. Are you _sure_ that you know all the causes of error in a
call to printf() -- such as output being written to a file on a disc
that has just filled up -- and have ensured that they can't happen?
You might like to use something like
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
static void error(void) /* BEWARE: This is UNIX-specific */
{ /* if you've closed stderr, we're sunk */
static char message[] = "Error in ?printf\n";
write(2, message, sizeof message - 1);
exit(EXIT_FAILURE);
}
void eprintf(char *format, ...)
{
va_list ap;
int t;
va_start(ap, format);
t = vprintf(format, ap)
va_end(ap);
if (t < 0) error();
}
void efprintf(FILE *stream, char *format, ...)
{
va_list ap;
int t;
va_start(ap, format);
t = vfprintf(stream, format, ap)
va_end(ap);
if (t < 0) error();
}
/* end of file */
--
Heuer's Law: Any feature is a bug unless it can be turned off.
More information about the Comp.lang.c
mailing list