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

前端 未结 4 1237
盖世英雄少女心
盖世英雄少女心 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: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)
    

提交回复
热议问题