Please consider the code below, in particular, observing that get_length
returns const size_t
.
#include <stdio.h>
const size_t get_length(void)
{
return 123;
}
void foo(void)
{
size_t length = get_length();
length++;
printf("Length #1 is %zu\n", length);
}
void bar(void)
{
// Still 123 because length was copied from get_length
// (copy ellision notwithstanding, which is not the point here)
size_t length = get_length();
printf("Length #2 is %zu\n", length);
}
int main(void) {
foo();
bar();
}
Output:
Length #1 is 124
Length #2 is 123
I am getting the following warning from clang-tidy:
Clang-Tidy: Return type 'const size_t' (aka 'const unsigned long')
is 'const'-qualified at the top level,
which may reduce code readability without improving const correctness
This message has two parts about the return type:
- Const correctness is not improved
- Code readibility is reduced
I understand the first part where, like in foo and bar, as the callers are not required to specify their local variables as const, ultimately const correctness is not improved, i.e. there is nothing preventing the callers from ignoring the fact that the callee returns a const object.
But I am not sure what is meant by "code readability is reduced" - is that simply because it may give some people false expectations that the return type shall never be modified? Or is there something else to it that only starts to make sense with more complex return types?
I ask because I do not consider readability to be reduced here and I am just not sure what the intention could have been behind the warning. Thanks.