lovecreatesbea...@gmail.com wrote:
Gcc only gives out a warning: `assignment discards qualifiers from
pointer target type' against code such as following:
$ type a.c
int main(void)
{
const char *pc;
char *p = pc;
return 0;
}
$ gcc -std=c99 -W -Wall a.c
a.c: In function `main':
a.c:4: warning: initialization discards qualifiers from pointer target
type
a.c:4: warning: unused variable `p'
$
`C: A Reference Manual, 5th', sec. 5.11.1 states that: `... In
standard C, the presence of any type qualifiers changes the
type: ...'. It says in sec 5.11.6: `Two (similarly qualified) pointer
types are compatible if they point to compatible types.'
In the above code snippet, `const char' and `char' are not qualified
similarly, they're not compatible types. pc and p are not compatible
pointers for they point to incompatible types. So, why isn't the
initialization above an error?
The relevant rules do not simply require that the two types be
compatible. It's a bit more complicated than that.
The relevant constraint is 6.5.16.1p1, which requires that for simple
assignment "both operands are pointers to qualified or unqualified
versions of compatible types, and the type pointed to by the left has
all the qualifiers of the type pointed to by the right;" In other words,
you cannot discard qualifiers from the pointed-at type during
assignment, but you can add them.
This is an initialization rather than an assignment, but the rules for
initializations cross-reference the rules for assignment in this
context (6.7.8p11).
Therefore, this code does contain a constraint violation, just not the
one you thought it had. Why gcc makes this a warning rather than an
error is a matter you should take up with the implementors of gcc. The
standard merely requires that there be at least one diagnostic message
for a constraint violation, and a warning message counts just as well as
an error message. The standard does not require that the program be
rejected.