I do understand the meaning of const
for pointers or structures that have to be passed by reference to a function. However in the example:
void foo(const int a);
the variable a
is passed on the stack. There is no harm to the caller to modify the content of the stack so const
looks pretty useless in this situation.
Furthermore, if I cannot modify a
, I can still make a copy of a and change this copy:
void foo(const int a)
{
int b = a;
b++;
}
In which situation does the const
keyword will be useful when applied to a scalar function argument (not a pointer)?
Code like void foo(const int a)
is not really meaningful, nor is it "const correctness" as such.
Sometimes overly pedantic programmers get the weird idea that they need to declare common parameters as const
just because a function doesn't modify the actual parameter. But most often, functions do not.
The point is, the variable is a copy of the original, so what your function does with it doesn't matter the slightest!
So this is not even a way of writing self-documenting code, because all it does is to tell the caller what's going on internally inside your function. The caller doesn't care and shouldn't care.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With