cpx
cpx

Reputation: 17577

Can I omit const qualifiers in declaration for pointer types?

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

Answers (3)

Bojan Komazec
Bojan Komazec

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:

  1. int* p
  2. const int* p (or int const* p)
  3. 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 p
  • void 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

Rob Kennedy
Rob Kennedy

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

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions