gcc: warning: large integer implicitly truncated to unsigned type

后端 未结 2 1103
余生分开走
余生分开走 2020-12-20 17:23
#include

int main()
{

    unsigned char c;
    c = 300;
    printf(\"%d\",c);
    return 0;
}

Is the output in any way predictable

2条回答
  •  生来不讨喜
    2020-12-20 18:13

    The result of the assignment should be predictable:

    3.9.1

    4 Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.17)

    17) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

    In addition, sizeof(char) is defined as 1, and sizeof(unsigned char) = sizeof(char), so you should see the same result regardless of implementation (assuming you don't have bytes with funny sizes other than 8).

    However, the warning is telling you that the result is probably not what you intended (for example, perhaps you overestimated the size of the unsigned type?). If that's what you intended, why not write 300 % (1 << CHAR_BIT) (assuming that 300 is somehow significant to you)?

提交回复
热议问题