"Martin" <martin.o_brien @[no-spam]which.net> writes:
I've searched this newsgroup's archives but couldn't find any posts that
provided any "rule of thumb" recommendations for use of const in function
parameters.
I appreciate there is no need for scalar variables to have const defined,
but how far should it go with pointers?
The Standard Library has functions defined that specify const, for example,
puts(const char *s) but why not go the extra bit and make it puts(const char
* const s)?
Any recommendations with rationale gratefully received.
`const char *s' means that the memory pointed to by `s' cannot be
modified through `s'. In the context of a function prototype, you can
consider this a promise: The function `puts' promises not to modify
the string you pass as argument.
`char *const s' means that the pointer itself cannot be modified. But
remember that `puts' has its own copy of the pointer. The caller doesn't
need to know if `puts' modifies its copy of the pointer, since that
wouldn't have any influence on the caller anyway.
For this reason, const (and volatile, and [in C99] restrict) qualifiers
on the parameter itself (but not on what the parameter points to, if it
is a pointer) can always be omitted in prototype declarations. It is
valid to declare, e.g., the following prototype
void foo (int a, int *b, const int *const *c);
and then define the function as
void foo (const int a, int *const b, const int *const *const c)
{
/* ... */
}
Martin