0

From what I understood about using the const type qualifier with a pointer, is that it depends where you use it.

const MyType *

Would mean that the location cannot be modified, but the value at the location can.

MyType const *

Would mean that the location can be modified, but not the value at the location.

From this, I would seen no reason for the following not to be valid,

const MyType const *

To define a pointer whose location is fixed, and for which the value pointed to cannot be modified. However, this is throwing "same type qualifier used more than once." Should I ignore this? Is my understanding of const semantics in the context of pointers flawed?

ophilbinbriscoe
  • 137
  • 1
  • 8

2 Answers2

5

You are slightly mistaken about the syntax. In fact

const MyType *

and

MyType const *

mean the same thing: the underlying MyType object is constant. The syntax for making the pointer itself constant is:

MyType * const

Thus if you want both to be constant, you would use:

MyType const * const

Or:

const MyType * const

A way to remember this is: the thing which is constant is the thing immediately to the left of the keyword const (which is * for pointer or MyType for the object), unless there is nothing to the left: in which case it is the thing to the right.

Smeeheey
  • 9,906
  • 23
  • 39
2

const MyType * and MyType const * are the same thing. They both mean pointer to const, i.e. the pointee is const. So for const MyType const *, you'll get the error because the const qualifier is used twice for the same thing.

What you want might be MyType const * const(note the position of const and *), which is a const pointer to const, i.e. the pointer itself and the pointee are both const. You could read it from right to left as "const pointer to const MyType".

songyuanyao
  • 169,198
  • 16
  • 310
  • 405