Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit ignore warning from -Wcast-qual: cast discards ‘__attribute__((const))’ qualifier from pointer target type

Tags:

c

gcc

warnings

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.

like image 238
ext Avatar asked Nov 06 '12 11:11

ext


2 Answers

#include <stdint.h>

const char * ptr = buf;
....
char * p = (char *)(uintptr_t)ptr;

Or, without stdint.h:

char *  p = (char *)(unsigned long)ptr;
like image 179
Bruce K Avatar answered Oct 16 '22 03:10

Bruce K


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.

like image 44
jclin Avatar answered Oct 16 '22 02:10

jclin