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

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

提交回复
热议问题