C++ Function Prototypes a\And Variable Names Versus Data Types Only
When declaring a function prototype in C++ is there a difference between the following:
void SomeFunction( int Argument )
{
//Stu开发者_StackOverflowff
}
Versus
void SomeFunction( int )
{
//Stuff
}
Essentially what I'm asking, is why do you write a variable argument name in the prototype of the function rather than just the data type?
Argument names are not needed for compiler in function declarations. It is for human consumption. They give additional information on what the function is doing. Good function names coupled with good argument names serve as instant documentation for your method.
You need an argument name if you're actually going to use the argument. Some compilers (Microsoft VC++ for example) will give you a warning if you name an argument but don't use it anywhere in the function.
P.S. What you've used in your example isn't a prototype, but an actual function definition. In a prototype, the argument name is purely optional.
an additional comment concerning the difference of "declaring" and "defining". You examples both are definitions:
void SomeFunction( int Argument )
{
//Stuff
}
A prototype would be a declararation and would look like this:
void SomeFunction( int ) ;
So, you can have in your header a declaration like above. Then in your cpp you define the function like this:
void SomeFunction( int Argument )
{
Argument = Argument + 1;
}
As you see the declaration does not specify an argument name, but the definition then does specify it and uses it.
You don't have to write an argument name in the definition, nor in the declaration. If you do, they don't even need to be the same. You must write one if you plan to actually use the argument.
A function prototype doesn't need parameter names, but it does need the types of the variables. Each of these are valid:
void function(int);
void function(int param);
The prototype is used so you can define functions in any order. However, if you want to see the parameter names (like when you hover over the function), the names must be in the prototype. If you don't have a prototype, you will see the names from the definition.
A function definition can double as a declaration if there is no prototype, but it must be defined before the function is called. Of course, the variable names in the definition will be used.
Parameters must have names in the definition, but the names are optional in prototypes.
精彩评论