static char buf[8];
void foo(){
const char* ptr = buf;
/* ... */
char* q = (char*)ptr;
}
The above snippet will generate \"warnin
#include <stdint.h>
const char * ptr = buf;
....
char * p = (char *)(uintptr_t)ptr;
Or, without stdint.h:
char * p = (char *)(unsigned long)ptr;
Bit late, but you can also do this without mucking with warnings at all:
static char buf[8];
void foo(){
const char* ptr = buf;
/* ... */
char* q = buf + (ptr-buf);
}
You end up with q = buf + ptr - buf = ptr + buf - buf = ptr
, but with buf
's constness.
(Yes, this allows you to remove const
from any pointer at all; const
is advisory, not a security mechanism.)
In GCC 4.2 and later, you can suppress the warning for a function by using #pragma. The disadvantage is you have to suppress the warning across the whole function; you cannot just use it only for some lines of code.
#pragma GCC diagnostic push // require GCC 4.6
#pragma GCC diagnostic ignored "-Wcast-qual"
void foo(){
const char* ptr = buf;
/* ... */
char* q = (char*)ptr;
}
#pragma GCC diagnostic pop // require GCC 4.6
The advantage is your whole project can use the same warning/errors checking options. And you do know exactly what the code does, and just make GCC to ignore some explicit checking for a piece of code.
Because the limitation of this pragma, you have to extract essential code from current function to new one, and make the new function alone with this #pragma.
As long as you are fine with GCC/clang specific code then this should do the job:
#define CONST_CAST2(TOTYPE,FROMTYPE,X) ((__extension__(union {FROMTYPE _q; TOTYPE _nq;})(X))._nq)
#define CONST_CAST(TYPE,X) CONST_CAST2 (TYPE, const TYPE, (X))
const char *ptr = buf;
char *q = CONST_CAST(char *, ptr);
Alternatively, a modified version based on Is cast of pointer to anonymous union valid in C11?:
#define CONST_CAST2(TOTYPE,FROMTYPE,X) ((union {FROMTYPE _q; TOTYPE _nq;}){._q=constBoo}._nq)