I always wondered if it is a good practice to have always prefer const
parameters when I can ? On one side you tell the compiler that this variable won't be mutated inside the function's scope so it can do optimizations under the hood, but on the other hand it does not affect the caller since arguments are passed by copy, so it can make the code bloated with const
s everywhere and thus less readable.
Does someone know what kinds of optimisations are done under the hood by compilers on const
parameters ? Can it optimize by passing the variable as reference without copying it for example ? Are there concurrency implications that we should be aware of ? (eg. when mutating the variable in another thread while the function is running).
Are the pros worth the cons ?
From C17 6.5.2.2 paragraph 2:
… Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter.
From C17 6.7.6.3 paragraph 15:
… (In the determination of type compatibility and of a composite type, each parameter declared with function or array type is taken as having the adjusted type and each parameter declared with qualified type is taken as having the unqualified version of its declared type.)
This effectively means that qualifiers such as const
in the immediate type of the function parameter are ignored by the caller, and are only meaningful to the called function itself, where they serve the same role as qualifiers in local variables.
It also means that these function declarations are compatible:
int foo(int a);
int foo(const int a);
If the parameter is declared const
in the function definition, then the compiler can treat the parameter the same way as a variable defined const
with an initializer:
int foo(const int a)
{
const int b = 42;
/* this is not a great example! */
return a + b;
}
When declaring the function in a shared header file, I would recommend declaring the parameter without the qualifier, because it is not relevant to callers of the function.