Quote: Void Cast Isn't Popular

Submitted by Jeremy
on November 5, 2007 - 3:32am

"The (void) cast isn't particularly popular practice. Did you find that it actually does anything useful?"

Can be informative

Lawrence D'Oliveiro (not verified)
on
November 6, 2007 - 3:25am

I think having to explicitly cast a function result to void helps to make it clear that you're throwing it away. Some functions return important information in their results. For instance, even a simple thing like

(void)unlink(filename);

makes it explicit that you're ignoring any error return from the unlink call.

Explicit

Anonymous (not verified)
on
November 11, 2007 - 12:34pm

(void)unlink(filename); makes it explicit that you're ignoring any error return from the unlink call.

So does unlink(filename); since you're not storing the return value anywhere ;-) Generally I dislike a cast where it's not required (and it's rarely required, at least in user-space).

There's a balance to strike here

on
November 6, 2007 - 5:27am

Unless the function has an attribute saying "return value should not be ignored" (and the (void) cast is used explicitly to override it), most of the time the (void) cast is useless noise.

I've actually seen style guides that suggest that every ignored return value should be cast to void. I think that's utter nonsense. Did you know printf() returns a value? Most people don't. So does strcat(), but I can't remember the last time I used its return value. One particular book though insisted on putting (void) in front of every such case. It seemed like every 2nd line of code had a (void) cast. Clearly noise.

So, I'd save that prescription solely for a handful of functions, ones for which it's very questionable to ignore the return value, and I'd mark those __attribute__((warn_unused_result)) in the headers. Examples in my book include malloc, calloc, realloc, open, fopen and so on. I'm not sure that unlink rises to that level for me.

Lest you think I'm a hypocrite, I do use a related feature of GCC's, -Wunused-parameter and the corresponding (void) casts for parameters I want to explicitly ignore. (This can happen when you're passing around function pointers, and some callbacks implement a degenerate case.) You just need to find a reasonable threshold so that (void) doesn't comprise 10% of the characters in any given source file. (Or even 1% for any "normal" length file.)

--
Program Intellivision and play Space Patrol!