Type conversion warning after bitwise operations in C

后端 未结 4 1241
傲寒
傲寒 2021-02-20 05:29

How do you explain that line 7 gets a warning, but not line 5 or line 6?

int main()
{
    unsigned char a = 0xFF;
    unsig         


        
4条回答
  •  后悔当初
    2021-02-20 05:50

    Compilers are built by people and they don't have infinite time to figure out all arithmetic possibilities to decide, which cases are worth issuing a warning.

    So I believe (attention opinion) that compiler engineers would go the following way:

    • generally issue a warning if code looks as if it could be wrong.
    • find all obvious cases where the compiler can be corrected to work easily.
    • leave the rest of the warnings as false positives, because the person either knows what he's doing or will be relieved that the compiler is warning.

    I would expect people to write code where either the result is casted to (unsigned char) or where the outermost operator masks all higher bytes with a constant.

    • a = (unsigned char) ( /* some obscure bit-wise expressoin */ ); would be OK then
    • a = 0xff & ( /* some obscure bit-wise expressoin */ ); also OK

    if you know that your compiler translates those two patterns correctly the other cases shouldn't bother you too much.

    I've seen compilers that would issue a warning because of a = a | b; so GCC not giving a warning is a free bonus. it might be, that gcc just infers the constant assignment in a | b and therefore replaces it with 0xff | 0xff which is known to work without problems. If that happens though I don't know why it cannot derive the constant value of a in the other statements.

提交回复
热议问题