This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: -Wcast-qual and casting away


Richard Guenther wrote:
> On Thu, May 21, 2009 at 1:50 PM, Andreas Schwab <schwab@linux-m68k.org> wrote:
>   
>> Ian Lance Taylor <iant@google.com> writes:
>>
>>     
>>> Consider this C/C++ program:
>>>
>>> extern void **f1();
>>> void f2(const char *p) { *(const void **)f1() = p; }
>>>
>>> If I compile this program with g++ -Wcast-qual, I get this:
>>>
>>> foo2.cc:2: warning: cast from type ‘void**’ to type ‘const void**’ casts away qualifiers
>>>       
>> In a sense this warning is actually correct: this is storing a const
>> char * into a void * object, which is where the qualifier is lost.  IMHO
>> having a warning for this questionable operation is a good thing.
>>     
>
> I don't think so.
>
> extern char **f1();
> void f(char *p)
> {
>   *(const char **)f1() = p;
> }
>
> warns the same. typeof(*(const char **)) should still be const char *.
>   
It seems the rules for the warning follow the same rules for whether
such qualifier changes are allowed in implicit conversions (or named
casts other than const_cast).

Let's say char** -> const char** is allowed silently. Then the program
below is silently violating const correctness:
char* pc;
char** ppc = &pc;
const char** cppc = ppc; // Silently allowed?
const char cc = 0;
*ppc = &cc; // Silently allowed, pc now points to cc
*pc = 1; // Silently allowed, but changes cc

The conversion T** -> const T** is unsafe. That's all there is to it.
The warning is correct.
Cast to T const* const* instead.

Sebastian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]