Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c++ - Why do function prototypes include parameter names when they're not required?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • If someone reads your header file, they can tell at a glance what each parameter is used for.
  • If you use a fancy IDE, it can show you the parameter names when you begin typing the function call.
  • Documentation tools like Doxygen can parse the parameter names and show them in the documentation.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...