I'm confused about why we need to pass void
into C functions:
int f(void) { return 0; }
versus
int f() { return 0; }
What is the proper thing to do and why?
In C and C++A function with void result type ends either by reaching the end of the function or by executing a return statement with no returned value. The void type may also replace the argument list of a function prototype to indicate that the function takes no arguments.
The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.
It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both.
In C, int f()
is an old-style declaration. It says that f
expects a fixed but unspecified number and type(s) of arguments. For example, given int f() { return 0; }
, the compiler won't complain about f(42)
, or f("hello, world")
(though the behavior of such a call is undefined).
int f(void)
explicitly says that f
takes no arguments.
(C++ has different rules; Stroustrup wasn't as concerned about backward compatibility with old C code.)
It's a vestige of C.
f(void)
takes no arguments, so f(1)
is invalid.
f()
means that the parameters are unspecified, so f(1)
is valid here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With