Reputation: 17577
For a function definition which contains the declaration of type void foo(const int )
Both of the following declarations are valid.
void foo(const int); // valid
void foo(int); // valid, const can be omitted.
But if a function definition contains a declaration of type void foo(const int*)
omitting const is ilegal:
void foo(const int *); // valid declaration
void foo(int *); // error: const cannot be omitted.
Why is const
cannot be omitted in the function declaration if its parameter has pointer types? What makes the difference?
Upvotes: 2
Views: 226
Reputation: 9536
Function deals with the copy of the passed argument. If that's integer, you can omit const
as original will not be touched anyway. In case of the pointer to int type there are three options:
int* p
const int* p
(or int const* p
)const int* const p
(or int const* const p
)const
can be applied to pointed object, pointer itself or to both. What you pass as an argument is pointer so you can omit const
for it as its copy is passed to function. So (2) and (3) can be used interchangeably (only when used as function argument type!). But const
for pointed object type makes difference:
void foo(const int* p);
// function cannot modify pointed integer object through pvoid foo(int* p);
// function can modify pointed integer object through p In both cases function can modify p
within function, but those changes are not reflected on the original pointer's value.
Upvotes: 2
Reputation: 163317
You can only omit the const specifier when it's applied directly to the parameter. In the pointer case, it's applied to the thing being pointed at, not the pointer itself, so there's an extra level of indirection between const and the parameter. You could omit it in this case:
void foo(int* const);
void foo(int*);
Upvotes: 3
Reputation: 272657
const int x
means that x
is read-only inside the function. The outside world doesn't care either way; the function is working with a copy of the argument.
However const int *p
means that p
points to something that is read-only. The outside world does care about this; it's a promise that the pointee can't be modified.
The corollary of this is that the following two declarations are equivalent:
void foo(const int *);
void foo(const int * const);
Upvotes: 3