The omission of void
in parameters means that the function takes any number of arguments:
Suppose a program:
void func() {
}
void func2(void) {
}
int main(void) {
func(2);
func2(2);
}
Now compiling it with gcc -std=c11 -Wall -pedantic test.c
, you get errors from func2
only:
test.c: In function ‘main’:
test.c:9:5: error: too many arguments to function ‘func2’
func2(2);
^
test.c:4:6: note: declared here
void func2(void) {
That is, it is not a compile time error with GCC to call void func();
with arguments, while it is compile time error to call void func2(void)
with arguments. Even though the function does not have any parameters, it is still possible to call it with any number of arguments.
However, even if this does compile, the 6.5.2.2 Function calls says that "If the number of arguments does not equal the number of parameters, the behavior is undefined." (and func
was called with 1 argument, but has no parameters).
The C11 standard n1570 working draft says the following:
6.11.6 Function declarators
- The use of function declarators with empty parentheses (not prototype-format parameter
type declarators) is an obsolescent feature.
(Fun fact: the standard itself uses int main()
in its examples).
As for the return
statement, it can be omitted from a function returning void, if it is the last statement. Return has 2 uses - terminate the execution of the function and specify the value returned to a caller.
The standard draft says:
- A
return
statement terminates execution of the current function and returns control to
its caller. A function may have any number of
return
statements.
Any here is taken to mean that both functions returning a value or functions that do not return a value (returning void
) are allowed to have no return
statements.
The 6.9.1 in the draft on function declarations says:
- If the
}
that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined
Thus omitting a return statement is undefined behaviour if the function returns a value (not void
), and the caller uses the value. (As an exception the standard also says that it is specified behaviour that omitting a return
statement in main()
is now equivalent to returning 0).