Explicitly ignoring the warning from -Wcast-qual: discards the "__attribute __ ((const)) classifier from the target pointer type

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 accidentally write to memory, I should not write.

But now I want to discard const for only one event (not for the whole file or project). The memory that it points to is writable (like buf above). I would prefer not to drop const from ptr , as it is used elsewhere, and storing pointers (one const and one non-constant) seems like a bad idea.

+7
source share
3 answers

In GCC 4.2 and later, you can suppress a warning for a function using #pragma. The disadvantage is that you must suppress the warning throughout the 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 that your entire project can use the same warning / error checking options. And you know exactly what the code does, and you just force GCC to ignore some explicit verification of the code part.
Due to the limitations of this pragma, you need to extract the main code from the current function to a new one and make a new function yourself with this #pragma.

+4
source
 #include <stdint.h> const char * ptr = buf; .... char * p = (char *)(uintptr_t)ptr; 

Or, without stdint.h:

 char * p = (char *)(unsigned long)ptr; 
+7
source

The bit is late, but you can also do this without warning with warnings:

 static char buf[8]; void foo(){ const char* ptr = buf; /* ... */ char* q = buf + (ptr-buf); } 

As a result, you get q = buf + ptr - buf = ptr + buf - buf = ptr , but with the constant buf .

(Yes, this allows you to remove const from any pointer in general, const is an advisory tool, not a security mechanism.)

-one
source

All Articles