Is there a difference between foo(void) and foo() in C++ or C?

0 votes
asked Sep 9, 2008 by landon

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?

3 Answers

0 votes
answered Sep 9, 2008 by paul-tomblin

In C, you use a void in an empty function reference so that the compiler has a prototype, and that prototype has "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.

0 votes
answered Sep 9, 2008 by kyle-cronin

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.

0 votes
answered Sep 9, 2008 by drpizza

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++).

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...