Stupid const question

Nov 1, 2010 at 10:32am
Hi all. Why does this code cause a compiler error ("you cannot assign to a variable that is const"). I thought the int wasn't const?

int a = 72;
int* const pint2 = &a;
*pint2++;

Cheers
Nov 1, 2010 at 10:37am
As i can see the problem is not the int* const pint2 = &a; because you can pass a non cast variable into a cast.Your problem is here *pint2++; ,pint2 is const so you can't modify it. cheers :)
Nov 1, 2010 at 10:39am
Yes, as you say, pint2 is const but *pint2 isn't (or so i thought).
Nov 1, 2010 at 10:47am
Look there are 3 ways you can use your const

Ι)char *const cp;
ΙΙ)char const* pc;
ΙΙΙ)const char* pc2;


The first is a const pointer to a char ,its address doesn't change ,only its value.
The second is a pointer to a const char //You can change its address but not its value
The third is the same as the second one.

So you belong in the second type,you try to change the value which is contained in a .This is not allowed!
Last edited on Nov 1, 2010 at 10:47am
Nov 1, 2010 at 10:50am
It's not a stupid question.

pint2 is a pointer to a constant int. You're trying to assign it a pointer to non-constant int (&a).

You may find this useful.
http://www.cplusplus.com/forum/beginner/10602/
Nov 1, 2010 at 10:51am
How do I belong 'in the second type'. My declaration has the same form as the first one.
Nov 1, 2010 at 10:54am
kbw, thanks. However, unless I've misunderstood you, the compiler has no problem at all with these two lines:

int a = 72;
int* const pint2 = &a;

Only the last one:

*pint2++;
Nov 1, 2010 at 10:59am
Look if you write it this way is correct :

int a = 72,b=60;
const int* pint2 = &a;
*pint2++;

Because is a const pointer to changeable value!
Nov 1, 2010 at 11:03am
Yes, thanks, but what I was after is *why* doesn't the code in my original post compile?
Nov 1, 2010 at 11:10am
The only change you can do in your original code is this :

int a = 72,b=70;
int* const pint2=&a;
*pint2=b;

because is a pointer to a const value.You can not change its value but you can change where it shows!!!Here *pint2=b; i make him to show a new value!
Nov 1, 2010 at 11:17am
Thanks for your help. I'm confused because I have read that a declaration like this one

int* const pint2 = whatever;

is declaring a *const* pointer to a *non-const* int.
Nov 1, 2010 at 11:53am
I've just got the real answer to this from another forum. The reason my code doesn't compile was down to operator precedence. In this line:

*pint2++;

The ++ operator is applied before the * operator meaning it therefore is applied to the pointer not the int.
Nov 1, 2010 at 12:44pm
Dum spiro spero
Topic archived. No new replies allowed.