Reputation:
A function declared
void f(const char * const p) { ... }
means that it takes a constant pointer to a constant character. But, with the variable p
scoped only within the function itself and its usage hidden from the callee, does it matter if the second const
is there?
In other words, wouldn't the following be semantically identical to the first from the perspective of the callee?
void f(const char *p) { ... }
Upvotes: 2
Views: 201
Reputation: 72697
Yes. You tell the compiler that you won't modify p
in that function. This allows the compiler certain optimizations, e.g. if p
is already in a register, there's no need to save it and no need to allocate a new register.
It also causes the compiler to issue a diagnostic should you attempt to modify p
, eg. ++p
or p = ...
because that violates the promise you made.
Upvotes: 1
Reputation: 11317
The first const indicates that you can't change the data is pointing to, the second indicates that this pointer can't be overwritten.
So, for a caller of this function, it doesn't matter. For the implementation of the function, it can be useful, though it will only have effect locally.
Upvotes: 2
Reputation: 27565
The second const
(the one after the *
) doesn't matter from the callee point of view.
But it does matter from the point of view of the function body.
The second const
makes sure that you can't make the pointer change its value (i.e. point to a different memory location).
It's comparable to declaring a simple primitive parameter as const
, like in void f(const int value) {}
Upvotes: 2
Reputation: 372982
Yes, I believe so. The additional const
here only means that in the implementation of f
, the implementer is not allowed to reassign p
to point to some other character or C-style string.
Upvotes: 0