0

what is the difference between

const int d=1; const int *p = &d; 

and

const int d=1; int const *p = &d; 

What can I do with the former and the latter ?

1
  • 1
    Note that int* const p is different. Commented Mar 16, 2014 at 17:27

3 Answers 3

4

There is no difference, they're completely identical.

The grammar of the language simply allows a certain amount of freedom for certain constructions, and CV-qualification of types is one of those situations. There are other examples (e.g. declarations like foo typedef int;).

Sign up to request clarification or add additional context in comments.

Comments

0

const int *p;

The declaration above declares a pointer p that points to a constant int. In other words, you can't change the value of the referand but you can change p itself.

int* const p;

The declaration above declares a constant pointer p that points to an int. In other words, you can change the value of the referand, but you can't change p. Also,

const int d = 1; int * const p = &d; 

is not legal. Taking the address of d yields const int*, and coversion from const int* to int* is not allowed (you could inadvertedly change the value of a constant object if it were).

You could make the conversion explicitly by using const_cast:

const int d = 1; int * const p = const_cast<int*>(&d); 

but it would still be illegal (undefined behaviour) to change the value of d through p.

Comments

0
const int *p; 

p is a pointer to a constant integer. You can change the value stored in p (thus it point somewhere else) but you can't change the value where p points to.

int* const p; 

p is a constant pointer to a non constant integer. You can't change the value of p, but change the integer where it points to

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.