I started learning the C language recently, and have noted the function "void()", however, I would like to know what it does and it's best points of application, also perhaps an alternative to void that is potentially more productive. Thank you.
问题:
回答1:
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)
{
....
}
回答2:
void
in C has three uses:
To declare that a function does not return a value:
void foo(int x);
To declare that a function does not accept parameters:
int baz(void);
(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.
回答3:
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.
回答4:
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
}