Search code examples
c++functionparametersconstantsforward-declaration

Use of 'const' for function parameters in forward declarations


Is there any reason to include the 'const' qualifiers for parameters in a function declaration if the function definition ignores them anyway? I assumed that the C++ compiler would enforce the usage of 'const' if it was forward declared, but this does not seem to be the case.

// Compiles without warnings.
void foo(const int x);
void foo(int x) {}
int main() {foo(0); return 0;}

Solution

  • No, there is no good reason to do that*.

    I'd argue that adding const in the declaration is a bad idea anyway, even if the definition has it too. Why? Because the language ignores it in the declaration, so there is no guarantee that the definition will have it. In any case, it is an implementation detail (essentially, choosing to use a const local variable), so it should appear, if needed, in the definition only.


    * "that" refers to top-level const. Pointer to const or reference to const is not ignored by the language.