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

前端 未结 4 1222
盖世英雄少女心
盖世英雄少女心 2020-12-19 05:03
static char buf[8];
void foo(){
    const char* ptr = buf;
    /* ... */
    char* q = (char*)ptr;
}

The above snippet will generate \"warnin

相关标签:
4条回答
  • 2020-12-19 05:36
    #include <stdint.h>
    
    const char * ptr = buf;
    ....
    char * p = (char *)(uintptr_t)ptr;
    

    Or, without stdint.h:

    char *  p = (char *)(unsigned long)ptr;
    
    0 讨论(0)
  • 2020-12-19 05:37

    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.)

    0 讨论(0)
  • 2020-12-19 05:55

    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.

    0 讨论(0)
  • 2020-12-19 05:55

    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)
    
    0 讨论(0)
提交回复
热议问题