Is the void
parameter only semantic or does it do anything I do not know?
int main() {
return 0;
}
int main(void) {
return 0;
}
Is the void
parameter only semantic or does it do anything I do not know?
int main() {
return 0;
}
int main(void) {
return 0;
}
In this case they are role definitions . It defines that the function can only be called with no argument being passed. Without void
you can call with argument passing. See in the ideone .
If it were statements, then it would be different. See below:
int funcao(void);
int funcao() {
return 0;
}
int funcao2();
int funcao2(int x, int y) { //válido
return 0;
}
In the prototype declaration, void
indicates that no parameter can be used to define the function implementation.
Contrary to what many people imagine and how it works in other languages, the use of the signature function funcao()
it just means that no parameter is set explicitly, giving you the freedom to do as you want.
The recommendation in C is to always use void
in the prototype declaration, if it is present. In C ++ it is not necessary, the language assumes that there will be no parameters.
In C, when the signature of a function has only the parameter void
, it means that this function does not receive any parameters when called.
There is a large difference between int foobar();
and int foobar( void );
. In the first case, the function was only declared and does not have a prototype. In the second case, the function was declared together with a prototype.
According to the C99 standard, the definition of functions is not recommended because it is obsolete, let's see:
6.11.6 Function declarators
The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.
6.11.7 Future language directions, Function declarators
The use of function definitions with separate parameter identifier and declaration lists (not prototype-format parameter type and identifier declarators) is an obsolescent feature.
It is not necessary to use void
when declaring / implementing a function that does not receive any parameters, however, it is a good practice that aims to optimize the readability and understanding of the code, facilitating the differentiation of when the function is being and when it is being declared.
Statement Only:
int foobar(); /* Evite Declarar Funções Sem Protótipo! */
Declaration and prototype:
int foobar( void ); /* Boa Prática! */
Definition / Implementation:
int foobar( void ){
return 0;
}
Call:
n = foobar();
I hope I have helped!