On Wed, 12 Sep 2007 06:33:40 -0700, Laurent Deniau wrote:
On 12 sep, 13:31, Michal Nazarewicz <min...@tlen.plwrote:
>Laurent Deniau <Laurent.Den...@gmail.comwrites:
I am looking for the "cleanest" way to cast away the constness of a
pointee in C89, something like const_cast<T*>() in C++. Actually, I
am using:
#define CONST_CAST(typename,value) \
(((union { const typename cv; typename v; }*)&(value))->v)
which requires value to be an lvalue, but avoid compiler warning
(gcc) comparing to the brute force of ((typename)(value)):
??? What's wrong with the "brute force" solution? I consider your
macro to be way less cleaner then plain casting.
but it warns if value is not of type typename while "brute force"
doesn't.
Not reliably. Depending on the compiler version and compiler options, you
may run into a warning about a violation of the aliasing rules. With the
compiler options I normally use, this warning is not enabled.
Additionally, you still break C's rules, including the aliasing rules.
It's just in a way that gcc doesn't warn about.
> Following code compiles w/o
any errors:
#v+
int main(void) {
int ret = 0;
const int *cv = &ret;
int *v = (int*)cv;
return *v;}
#v-
gcc emits a warning on this code (and I always use -Werror ;-):
const.c: In function 'main':
const.c:4: warning: cast discards qualifiers from pointer target type
Only if you use the -Wcast-qual option. This warning option is not
enabled by default and not included in any warning group. So you are
explicitly asking gcc to let you know when you are casting away
constness, and then you decide you would like to find a way to cast away
constness in a way that gcc can't detect because you don't like the
warnings you're getting. The proper solution is to not use that compiler
option in the first place.