I've seen methods with the following signature:
void foo (void);
They take no argument, however I'm wondering whether doing this is useful or not. Is there a reason why you would want to do it?
main(void) will be called without any parameters. If we try to pass it then this ends up leading to a compiler error.
If a function is not meant to take any parameters, specify that by using void in the parameter list. int printf(const char*, ...); declares a function that can be called with varying numbers and types of arguments.
In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal. When used in a function's parameter list, void indicates that the function takes no parameters.
A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.
This is a holdover from older versions of C, where foo()
meant "a function with an unknown number of parameters" and foo(void)
means "a function with zero parameters." In C++, foo()
and foo(void)
both mean "a function with zero parameters", but some people prefer the second form because it is more explicit.
The C++03 standard says (emphasis mine):
8.3.5.2
The parameter-declaration-clause determines the arguments that can be specified, and their processing, when the function is called. [Note: the parameter-declaration-clause is used to convert the arguments specified on the function call; see 5.2.2. ] If the parameter-declaration-clause is empty, the function takes no arguments.
This means that if you are talking to the compiler it's just a matter of taste.
If you are writing code that will be read by others, then the C++ way of doing things is
void foo();
The other form remains valid only for reasons of compatibility with C, where there was a difference among the two signatures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With