I always thought that a function prototype must contain the parameters of the function and their names. However, I just tried this out:
int add(int,int);
int main()
{
std::cout << add(3,1) << std::endl;
}
int add(int x, int y)
{
return x + y;
}
And it worked! I even tried compiling with extreme over-caution:
g++ -W -Wall -Werror -pedantic test.cpp
And it still worked. So my question is, if you don't need parameter names in function prototypes, why is it so common to do so? Is there any purpose to this? Does it have something to do with the signature of the function?
In a prototype, parameter names are optional (and in C/C++ have function prototype scope, meaning their scope ends at the end of the prototype), however, the type is necessary along with all modifiers (e.g. if it is a pointer or a reference to const parameter) except const alone.
Examples: int add( int a, int b ); int add( int, int ); Note that the function prototypes end with semicolons, indicating that this is not a function, but merely a prototype of a function to be provided elsewhere. Note also that the variable names are not required in the function prototype.
Parameters allow us to pass information or instructions into functions and procedures . They are useful for numerical information such as stating the size of an object. Parameters are the names of the information that we want to use in a function or procedure.
A function prototype is a definition that is used to perform type checking on function calls when the EGL system code does not have access to the function itself. A function prototype begins with the keyword function, then lists the function name, its parameters (if any), and return value (if any).
No, these are not necessary, and are mostly ignored by the compiler. You can even give them different names in different declarations; the following is entirely legal:
int foo(int bar);
int foo(int biz);
int foo(int qux) {
...
}
(The compiler does check that each name is used only once in the same argument list: int foo(int bar, int bar);
is rejected.)
The reason to put them in is documentation:
Parameter names are completely optional, and have no effect on compilation. They may be placed there for better readability of code.
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