Saturday, March 25, 2006

The difference between foo() and foo(void)

We often see two different ways to declare a method that takes no arguments. The two common forms are:

  1. int foo();

  2. int foo(void);

Which one is correct? And what's the difference?

Well, in C++ the two forms are equivalent and they both declare a function that takes no arguments. If you try to call the function and pass in an argument, the compile will give an error.

On the other hand, C and Objective-C both treat the two forms differently. In these languages the first form declares a function that takes an unknown number of arguments, whereas the second form declares a function that takes no arguments at all. So, in C the following is valid code:
int foo() {
return 5;
int main() {
return foo(1, 2, 3);
The compiler doesn't complain, and the code runs fine (a C++ compiler would give an error on this same code).

Generally what you want in C and Objective-C is to use the second form and include the explicit void to indicate that the function should take no arguments. However, it's more common in C++ to use the first form because it's equivalent and shorter.

No comments: