This is the mail archive of the gcc-patches@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: [PATCH]: Fix problematic -Wcast-qual cases using new CONST_CAST macro


On 7/27/07, Kaveh R. GHAZI <ghazi@caip.rutgers.edu> wrote:
> This patch addresses problems in achieving clean -Wcast-qual results.
> The issue is that there are certain legitimate situations where it is
> impossible in C to avoid casting away const-ness.  Such examples IMHO
> include:
>
> 1.  Passing const argv strings to execv-like functions.
>
> 2.  Initializing const allocated objects.
>
> 3.  Free'ing const objects from #2.
>
> (It's been suggested that adding a specialized const_free(const void*)
> to libiberty could hide casting away const-ness.  However that only
> solves one of the above three cases.)
>
> So I added a mechanism to system.h that uses a union cast to get
> around -Wcast-qual.  I named the macro CONST_CAST(X) in honor of the
> C++ operator of similar utility.
>
> I believe all of the cases where I used it below fall into one or more
> of the above three categories.
>
> Tested on sparc-sun-solaris2.10, no regressions.  I used cc for stage1
> to make sure that the non-gcc case works.  I also tested it with
> gcc-3.4.6 to make sure that the union cast worked for older gcc
> versions.
>
> Okay for mainline?  (If someone approves the system.h mechanism, I'll
> install the rest as obvious.)

> +union gcc_constcast
> +{
> +  const void *cv;
> +  void *v;
> +};
> +#define CONST_CAST(X) ((__extension__(union gcc_constcast)(const void *)(X)).v)

Can you explain in how this is better than using an explicit cast to
the non-const
version like in memcpy ((char *)x, ...)?  At least it cannot detect
wrongly typed
arguments anymore due to the use of void*.  ATM we could do the following:

#define CONST_CAST(X) ((__extension__((union { __typeof__(X) _q; void
*v; })(X)).v)

and I'd suggest to create a __typeof__ that strips CV qualifiers to be
able to get
rid of the void* member in the union as well.

Richard.


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