Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are function argument names unimportant in c++ declarations?

Function argument names in declarations (that most likely reside in the header file) are seemingly completely ignored by the compiler. What are the reasons for allowing the following to compile using either declaration version 1 or 2?


implementation

void A::doStuff(int numElements, float* data)
{
    //stuff
}

declaration - Version 1

class A
{
public:
    void doStuff(int numElements, float* data);
}

declaration - Version 2

class A
{
public:
    void doStuff(int, float*);
}
like image 447
learnvst Avatar asked Apr 19 '12 09:04

learnvst


People also ask

What happens if one of the argument names in a function declaration does not match that of the corresponding function definition?

It is an error if the number of arguments in a function definition, declaration, or call does not match the prototype. If the data type of an argument in a function call does not match the corresponding type in the function prototype, the compiler tries to perform conversions.

How to call a function without arguments in C?

To call a function which takes no arguments, use an empty pair of parentheses. Example: total = add( 5, 3 );

Does it matter what order you put the arguments in to call a function?

Yes, it matters. The arguments must be given in the order the function expects them.

Does a function prototype have to include the names of parameters C++?

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.


2 Answers

The compiler only needs to know what kind of arguments the method requires. It's unimportant for the compiler how you call them.

The compiler needs to know the argument types for several reasons:

  • Decide which method to use if there are several methods with the same method name
  • Decide whether the input parameters are valid
  • Decide whether the parameters need to be casted
  • Decide how to generate the CODE to call the method and handle the response

However, I suggest to use the first header version. It helps other developers (and yourself) to use the functions and know what parameters have which meaning.

like image 96
Benjamin Schulte Avatar answered Oct 13 '22 21:10

Benjamin Schulte


Parameter names aren't part of the function signature. Unless you use them, you don't need to have names even in the function implementation.

like image 34
Luchian Grigore Avatar answered Oct 13 '22 19:10

Luchian Grigore