views:

74

answers:

6

Hi All,

I recently came across a rather unusual coding convention wherein the call for a function returning "void" is prefixed with (void).

e.g.

(void) MyFunction();  

Is it any different from the function call like:

MyFunction();  

Has it got any advantage or is it yet another needless but there coding convention of some sort?

+2  A: 

No, there isn't any difference -- what's being cast to void is the return value of the function.

I'd say it could make sense of you wanted to make explicit you're not using the return value (you're calling it for the side effects), but as the function already has void return, it doesn't make much sense.

Artefacto
+9  A: 

Some functions like printf() return a value that is almost never used in real code (in the case of printf, the number of characters printed). However, some tools, like lint, expect that if a function returns a value it must be used, and will complain unless you write something like:

int n = printf( "hello" );

using the void cast:

(void) printf( "hello" );

is a way of telling such tools you really don't want to use the return value, thus keeping them quiet. If you don't use such tools, you don't need to bother, and in any case most tools allow you to configure them to ignore return values from specific functions.

anon
I see. But then why would anybody want to do this for a function already returning void?
puffadder
Sure, but he said the cast was made for functions that return void.
Artefacto
@puffadder At a guess, the function's return type got changed at some point, but the calling code didn't.
anon
A: 

If the function returns something the void could avoid (!) a warning (indeed in no way I was able to make gcc warn me that the return value is lost) on some compilers (or lint tools); but more importantly, it makes clear that a return value is "thrown" away purposely (and not by mistake).

ShinTakezou
A: 

acedemically: a "function" always returns something, else it would be a procedure. So the Author of this code wants to say "i know this naming is wrong, but i will no change the name, so i make this disturbance visible"

Peter Miehle
A: 

Has it got any advantage or is it yet another needless but there coding convention of some sort?

No difference. It is a quite common convention e.g. in software testing to highlight the fact that in context the function return, if any, is safe to be discarded.

Dummy00001
A: 

In HPUX man pages it is quite common in example code to see a cast to void to get around lint warnings.

fprintf(mystream, "%s\n", "foo");

vs.

(void)fprintf(mystream, "%s\n", "foo");

That may be where the author of the code is coming from. IMO, this is not a great idea because most of the sprintf family, for example, call malloc. malloc will fail when there is not enough memory. SIGINT also causes the underlying write() syscall to interrupt and not write all of the buffer, for printf() family members.

jim mcnamara