static char buf[8];
void foo(){
const char* ptr = buf;
/* ... */
char* q = (char*)ptr;
}
The above snippet will generate "warning: cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Wcast-qual]"
. I like -Wcast-qual
since it can help me from accidentally writing to memory I shouldn't write to.
But now I want to cast away const for only a single occurrence (not for the entire file or project). The memory it is pointing to is writable (just like buf
above). I'd rather not drop const from ptr
since it is used elsewhere and keeping to pointers (one const and one non-const) seems like a worse idea.
#include <stdint.h>
const char * ptr = buf;
....
char * p = (char *)(uintptr_t)ptr;
Or, without stdint.h:
char * p = (char *)(unsigned long)ptr;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With