Nov 1, 2010 at 10:32am Nov 1, 2010 at 10:32am UTC
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 Nov 1, 2010 at 10:37am UTC
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 Nov 1, 2010 at 10:39am UTC
Yes, as you say, pint2 is const but *pint2 isn't (or so i thought).
Nov 1, 2010 at 10:47am Nov 1, 2010 at 10:47am UTC
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:47am UTC
Nov 1, 2010 at 10:51am Nov 1, 2010 at 10:51am UTC
How do I belong 'in the second type'. My declaration has the same form as the first one.
Nov 1, 2010 at 10:54am Nov 1, 2010 at 10:54am UTC
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 Nov 1, 2010 at 10:59am UTC
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 Nov 1, 2010 at 11:03am UTC
Yes, thanks, but what I was after is *why* doesn't the code in my original post compile?
Nov 1, 2010 at 11:10am Nov 1, 2010 at 11:10am UTC
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 Nov 1, 2010 at 11:17am UTC
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 Nov 1, 2010 at 11:53am UTC
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.