In C and C++, parameters can be declared const
when defining a function:
// without const
void foo(int i)
{
// implementation of foo()
}
// with const
// const communicates the fact that the implementation of foo() does not modify parameter i
void foo(const int i)
{
// implementation of foo()
}
From the caller's perspective, though, both versions are identical (have the same signature). The value of the argument passed to foo()
is copied. foo()
might change that copy, not the value passed by the caller.
This is all well, but one is allowed to use const
also when declaring foo()
:
void foo(int i); // normal way to declare foo()
void foo(const int i); // unusual way to declare foo() - const here has no meaning
Why is const
allowed by the C and C++ standards when declaring foo()
, even though it is meaningless in the context of such a declaration? Why allow such a nonsensical use of const
?
const
is a type qualifier: https://en.cppreference.com/w/cpp/language/cv
As such, they can be added to a type as part of the grammar itself. I suppose they didn't want to specify differently an argument and a variable. (it makes probably the implementation a little bit easier?)
Then the issue is that they don't participate to the signature when they refer to the argument itself (they are part of the signature when they refer for instance to the memory pointed by the argument), as you said in your question.
clang-tidy has a rule to remove the superfluous const
: https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html