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


Question

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
238
1/13/2017 11:12:13 PM

Accepted Answer

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

301
8/27/2017 2:52:34 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon