The following code compiles without warning on GCC but gives a warning in Visual Studio 2005.
const void * x = 0;
char * const * p = x;
x points to a constant object of unknown type, and p points to a constant pointer to char. Why should the assignment to p result in a warning?
Again, this is C, not C++. Thanks.
You have to read the following from right to left.
char * const * p = x;
For Example:
P points to a const pointer of type char.
At first I assumed you meant to take the address of x and wrote the code for that. Then I decided that x points to a pointer to char []. Both anyway, and it's still quite confusing:
The extra
const
before thechar
in the declaration ofp
prevents(**p)++
from compiling. However, the addedconst
before the declaration ofq
(in GCC) shadowswarning: dereferencing ‘void *’ pointer
witherror: increment of read-only location ‘**q’
for(**q)++
. Hope that helps, it has helped me a little :-)The C code is valid and a conforming compiler shouldn't warn as
const
ness is correctly preserved and conversion ofvoid *
to any pointer type (function pointers aside) is implicit.A C++ compiler is supposed to warn about the implicit conversion, but a warning about discarding the
const
qualifier is wrong and should be considered a compiler bug.What if
x
would point to, say, astruct Thing
as opposed to achar
? In that case, you'd be doing something with unspecified behavior. GCC tends to let you do this because it assumes that you're smart enough not to shoot yourself in the foot, but there is good reason for the warning.It happens because when you make a pointer of one type point to another type, sometimes it is done unintentionally (bug), so the compiler warns you about it.
So, in order to tell the compiler that you actually intent to do it, you have to do explicit casting, like this:
P.S. At the first place I wrote "most of the times is done unintentionally", but AndreyT made me reconsider it when he rightfully said that void * exists specifically for that purpose.
You cannot cast
const void
tochar *const
or evenchar *
. By dereferencingp
, you can now modify*(char *)(*x)
. This is a little known subtlety about pointers in C.A working type for
p
would be:And yes, I put
const
on the right like a man.