Need for prefixing a function with (void)
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:
MyFunctio开发者_运维技巧n();
Has it got any advantage or is it yet another needless but there coding convention of some sort?
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.
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.
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).
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"
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.
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.
精彩评论