Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why add void to method parameter list

Tags:

c++

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?

like image 975
Luchian Grigore Avatar asked Sep 14 '11 06:09

Luchian Grigore


People also ask

Is void parameter necessary?

main(void) will be called without any parameters. If we try to pass it then this ends up leading to a compiler error.

Why do we use void in the argument list of a function?

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.

What does void parameter mean?

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.

Can a void function take in 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.


2 Answers

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.

like image 153
Raymond Chen Avatar answered Sep 23 '22 11:09

Raymond Chen


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.

like image 23
Jon Avatar answered Sep 20 '22 11:09

Jon