This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: -Wcast-qual and casting away
- From: Gabriel Dos Reis <dosreis at gmail dot com>
- To: Ian Lance Taylor <iant at google dot com>
- Cc: gcc at gcc dot gnu dot org
- Date: Thu, 21 May 2009 12:29:34 -0500
- Subject: Re: -Wcast-qual and casting away
- References: <m3r5yjxcpw.fsf@google.com>
- Reply-to: gdr at integrable-solutions dot net
On Thu, May 21, 2009 at 12:10 AM, Ian Lance Taylor <iant@google.com> wrote:
> 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
>
> If I compile this program with gcc -Wcast-qual, I do not get any
> warning.
>
> Let's overlook the fact that the text of the g++ warning does not make
> any sense--I am certainly not casting anything away. ?The warning is
> conceptually plausible for the same reason that you can't assign a
> char** variable to a const char** variable without a cast. ?At least, I
> think one could make a argument that that is so. ?But it's not a *very*
> strong argument, as -Wcast-qual is documented to warn about cases where
> a type qualifier is removed, and that is manifestly not happening here.
> -Wcast-qual is useful to catch certain programming errors; I don't think
> anybody adding a const qualifier is actually making a mistake.
In fact, the contrary is true. The warning speaks the truth.
The implicit conversion is unsafe and the cast is explicitly
by-passing that const-safety built into the type system.
-- Gaby