In C or C++ what is the difference between function declaration and function signature?
I know something of function declaration but function signature is totally new to me. What is the point of having the concept of function signature? What are the two concepts used for actually?
Thanks!
The standard defines two terms: declaration and definition. A definition is a tentative declaration. However, the C99 and C++03 standards have slightly varying definitions.
From C++0x draft:
Also please note that top-level const and volatile on argument are not part of the signature, according to the standard. But some compilers get this wrong.
e.g.
has the same signature as
A function declaration is the prototype for a function (or it can come from the function definition if no prototype has been seen by the compiler at that point) - it includes the return type, the name of the function and the types of the parameters (optionally in C).
A function signature is the parts of the function declaration that the compiler uses to perform overload resolution. Since multiple functions might have the same name (ie., they're overloaded), the compiler needs a way to determine which of several possible functions with a particular name a function call should resolve to. The signature is what the compiler considers in that overload resolution. Specifically, the standard defines 'signature' as:
Note that the return type is not part of the function signature. As the standard says in a footnote, "Function signatures do not include return type, because that does not participate in overload resolution".
A function declaration is a prototype. A function signature indicates what is the return type and the parameters used that makes up the signature. Consider this:
Now, consider this scenario: a programmer is asked what is the function signature for
foo
:int
int
, nameda
andb
respectivelyThe function prototype on the other hand is to clue in the C/C++ compiler, on what to expect and if the signature does not match up with the prototype, the compiler will emit an error, along the context of 'function declaration error' or 'prototype mismatch'.
The function signature doesn't include the return type or linkage type of the function.
OK, Wikipedia disagrees with me on the return type being included. However I know that the return type is not used by the compiler when deciding if a function call matches the signature. This previous StackOverflow question appears to agree: Is the return type part of the function signature?