Reputation: 3676
With my compiler (Apple llvm-gg-4.2) this code:
void fun1(const char *s)
{
char* t = s+1;
}
void fun2(char *s)
{
char* t = s+1;
}
int main(void)
{
char* a;
fun1(a);
fun2(a);
}
gives this warning:
junk.c:3: warning: initialization discards qualifiers from pointer target type
on fun1 but not on fun2. Why?
Upvotes: 1
Views: 2259
Reputation: 755307
The reason why is in fun1
you are converting const char *
to a char *
. This is losing the const
qualifier and opening the door to modify data the function likely didn't intend to be modified.
To fix this change the fun1
body to
const char* t = s+1;
Upvotes: 3
Reputation: 36986
In fun1
, s
is a const char *
. When you do char* t = s+1;
, you "remove" that const
status from s
. Hence the "discards qualifiers". If this were C++, you would get a compiler error instead of a warning.
Upvotes: 3
Reputation: 5738
fun1 is taking const char* and is being assigned to char*
Whereas fun2 is taking a char* and being assigned to char* which is fine.
If you are assigning a constant pointer to a non-const pointer, this means you can modify the const pointer by using the const pointer
In this case, inside fun1 if you do t[0] = 'a'
its not legal because you are modifying const memory, which is why compiler warns you
Upvotes: 4