tags:

views:

3126

answers:

3

Consider these two function definitions

void foo(){}

void foo(void){}

Is there any difference between these two? If not, why is the void argument there? Aesthetic reasons?

+1  A: 

In C, you use a void in an empty function reference so that compiler has a prototype, and that prototype is "no arguments". In C++, you don't have to tell the compiler that you have a prototype because you can't leave out the prototype.

Paul Tomblin
"prototype" means the argument list declaration and return type. I say this because "prototype" confused me as to what you meant at first.
Zan Lynx
+9  A: 

I realize your question pertains to C++, but when it comes to C the answer can be found in K&R, pages 72-73:


Furthermore, if a function declaration does not include arguments, as in

double atof();

that too is taken to mean that nothing is to be assumed about the arguments of atof; all parameter checking is turned off. This special meaning of the empty argument list is intended to permit older C programs to compile with new compilers. But it's a bad idea to use it with new programs. If the function takes arguments, declare them; if it takes no arguments, use void.

Kyle Cronin
+45  A: 

The main reason is to achieve consistent interpretation of headers that are shared between C and C++.

In C:
void foo() means "a function foo taking an unspecified number of arguments of unspecified type"
void foo(void) means "a function foo taking no arguments"

In C++:
void foo() means "a function foo taking no arguments"
void foo(void) means "a function foo taking no arguments"

By writing foo(void), therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an extern "C" if we're compiling C++).

DrPizza
But if C++ had required the `void`, then it could have avoided the "most vexing parse" problem.
Adrian McCarthy
True, but there are so many other crappy parses in C++ there's no real point in kvetching about any one of them.
DrPizza