Modern compilers can optimize code when they see a const
. However, I've never seen the C standard library use const
for its non-pointer arguments. For example memcmp()
is an example of this. It has 2 const void *
arguments, but its third argument is size_t
.
Why is the standard library (and other libraries) designed this way? Why don't I see const size_t
or const int
in modern code?
C uses call-by-value. It does not help the compiler one bit to mark a function argument as const
(note that none of the arguments of memcmp()
is const
. The pointers arguments could also be declared const
, and you could have suggested that they should be: int memcmp(const void * const s1, const void * const s2, size_t const n);
. But they aren't).
The reason it would not help the compiler to mark function arguments const
is that a function argument is just, from the point of view of the function, a local variable. As long as the function does not take its address, it's very easy for the compiler to see that the variable is never modified.
In contrast, the const
modifiers that are part of memcmp()
's prototype (const void *s1
)
are part of its contract: they express that the function does not modify the pointed data. The const
modifier is never used this way for the argument themselves because the caller does not care if the function modify its arguments: they are just copies (again because C uses call-by-value).
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