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?
Those const
s mean different things. In
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
const void * ptr1
means that memcmp
will treat ptr1
as pointing to constant data and won't modify it; similarly for const void * ptr2
. Thus, the caller knows that the stored values won't be changed and can optimize accordingly. In a function call like
int result = memcmp(ptr1, ptr2, num);
the variables ptr1
, ptr2
, and num
are copied into the function. memcmp
makes no promises not to adjust them; it only promises not to adjust what the pointers point to. Indeed, it might increment/decrement any of the copied variables in order to step through the arrays if that proves efficient. If it wanted to promise not to change any of them, the declaration would be:
int memcmp ( const void *const ptr1, const void *const ptr2, const size_t num );
For simple data types (like pointers and integers), little (if any) optimization can be gained in this way, and the original specifiers of this function (and others) apparently saw no reason to prevent implementations from modifying the variables in fortuitous circumstances.