When can “void()” be used and what are the advantages of doing so

為{幸葍}努か 提交于 2019-12-04 21:05:59

There is no function called void, but a function can be declared with a return type of void. This means that the function doesn't return a value.

void DoSomething(...)
{
  ....
}

Update

void can also be used to indicate to the compiler that the function does not take any arguments. For example,

float CalculatePi(void)
{
 ....
}
John R. Strohm

void in C has three uses:

  1. To declare that a function does not return a value:

    void foo(int x);
    
  2. To declare that a function does not accept parameters:

    int baz(void);
    
  3. (DANGER WILL ROBINSON!) To declare a "universal pointer", that may be passed around as e.g. a magic cookie, or handed back to someone in a callback, there to be cast back to its original type.

    int register_callback(void (*foo)(void *baz), void *bar);
    

register_callback is called with a pointer to a void function that expects as parameter a pointer that presumably means something to it. At some (unspecified) time in the future, that function will be called, with bar as the parameter. You see this kind of thing in certain kinds of embedded executives and reusable device drivers, although not so much anywhere.

When void as function arguments is useful ?

#include "stdlib.h"
#include "stdio.h"

void foo();

int main()
{
    foo(5);    // Passing 5 though foo has no arguments. Still it's valid.
    return 0;
}

void foo()
{
    printf("\n In foo \n") ;
}

In the above snippet, though foo() prototype has no arguments it is still valid to pass something to it. So, to avoid such things to happen -

void foo(void) ;

Now it is guaranteed that passing anything to foo() would generate compiler errors.

I don't think there is a void() function.

However, the void keyword is used to indicate that a function doesn't return anything, e.g.:

void MyFunction() {
   // function body here
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!