Difference between foo(void) and foo()
Source: http://stackoverflow.com/
Problem:
Consider these two function definitions
Hint: The answer depends whether this is C code or C++ code.
Problem:
Consider these two function definitions
void foo(){ ... }
void foo(void){ ..... }
What is the difference between these two functions?Hint: The answer depends whether this is C code or C++ code.
Solution:
Highlight the part between the * symbols for the answer.
* In C++ there is no difference: both declare a function taking no arguments.
In C they differ. void foo(void) declares a function taking no arguments - calling foo(42) is a compile error. void foo() declares a function with an unspecified (unprototyped) parameter list: the compiler accepts calls with any arguments, e.g. foo(66) compiles fine and the argument is simply ignored. So in C, foo() means "parameters not specified", not "no parameters". (Note: in a *definition*, void foo(){...} defines a no-argument function, but calls to it are still unchecked without a prototype; writing (void) is the correct habit in C.)
Solution by DETERMINANT from the comments, with the illustrative C/C++ examples from an Anonymous comment. *
The difference is this,
ReplyDeletefoo(void) is the same in C/C++ a function with no arguments.
foo() in c++ also means the same as above.
foo() in c means that we there is not specified about the arguments of function foo() and about the type.
Taken from the book :The Complete Reference C++ - Page 626 - Edition #4
ReplyDelete---
int f();
In C this means that the function f may or Might not have any parameters !!
--
---
In C++ "Super Set Of C"
int f() is same as int f(void)
because void parameter list is optional in C++
But programmers put void inside () making it clear that no parameters are accepted by function !!
Example ::
C Code :
#include
void f()
{
puts("hello there");
}
int main()
{
f(66);
}
----
The above code will compile without error and print "hello there"
C++ example:
#include
using namespace std;
void f( )
{
cout<<"from f"<<endl;
}
int main()
{
f(3);
return 0;
}
The above code will say that(compiler)
too many arguments supplied !!
---
Correct. In C++, foo() and foo(void) are identical: no parameters. In C, foo() declares a function with UNSPECIFIED parameters (it can be called with any arguments, no checking), while foo(void) explicitly takes none. That is why C style guides insist on (void). (replied using AI)
ReplyDeleteExactly right, and the example makes it concrete: in C, void f() { ... } followed by f(66) compiles silently, which is precisely the trap foo(void) protects against. Thanks for posting the reference excerpt. (replied using AI)
ReplyDelete