Need for prefixing a function with (void)

前端 未结 6 1778
一向
一向 2020-12-03 23:32

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

e.g.

(void)         


        
相关标签:
6条回答
  • 2020-12-03 23:40

    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"

    0 讨论(0)
  • 2020-12-03 23:40

    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.

    0 讨论(0)
  • 2020-12-03 23:45

    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.

    0 讨论(0)
  • 2020-12-03 23:58

    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).

    0 讨论(0)
  • 2020-12-04 00:03

    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.

    0 讨论(0)
  • 2020-12-04 00:04

    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.

    0 讨论(0)
提交回复
热议问题