const pointer parameter assigned to a local variable inside a function
Code:
void func1(const int* p, int i)
{
int *q = p;
if (*q==i)
printf("very good");
}
I have to qualify the declaration of q with 'const' in order to avoid a gcc warning. Why? By declaring *p a const, I am saying nothing inside the function modifies *p, and indeed nothing does. So why does gcc give me
warning: initialization discards qualifiers from pointer target type
? Why does gcc discard the const-ness of *p? Yes, the function _may_ attempt to change *p through q, but the fact is it does not. And now gcc drops the const and actually the function now can change the value of *p!
Now I can change *p through q and gcc does not complain about assigning a value to a read-only memory (though still with that "discards qualifiers " warning):
Code:
void func1(const int* p, int i)
{
int *q = p;
*q = i;
}