Why is −1 > sizeof(int)?

后端 未结 4 814
[愿得一人]
[愿得一人] 2020-11-30 14:41

Consider the following code:

template class StaticAssert;
template<> class StaticAssert {};
StaticAssert< (-1 < sizeof(in         


        
4条回答
  •  时光取名叫无心
    2020-11-30 15:24

    It's simple and sad. In C/C++:

    1. most of the time, unsigned integer types have the semantic of modular integers (they represent equivalence classes)
    2. comparisons of unsigned integer types have the semantic of usual integer ordering, so that 1U < 2U (IOW 0U is the smallest unsigned value)
    3. sizeof has type size_t
    4. size_t is an unsigned integer type
    5. Point (1) implies that mixed arithmetic computations involving a signed and an unsigned integer are done in unsigned, modular arithmetic: this is the only possibility without violating "unsigned mean modular" rule. It's trivial to convert an integer to the equivalence class of integers equivalent to it. (Whereas going the other way requires the choice of an integer to represent the equivalence class.)
    6. Point (5) implies that -1 < 1U is interpreted as unsigned(-1) < 1U, and unsigned(-1) = - 1U, and obviously - 1U < 1U, so -1 < 1U is true.
    7. Points (1,3,4) imply that sizeof something acts (mostly) as an equivalent class (!!!).
    8. All this imply that -1 < sizeof something

    The conclusion: this is a design error inherited from C.

    Rule:

    Only use unsigned types for modular arithmetic, bits manipulations (&, |, ^, <<, >>, ~ operators), byte manipulations (unsigned char means "byte" in C/C++), and characters (unsigned char means character in C/C++).

    Do not use unsigned types to do arithmetic.

    If a function expects an integer value that should never be negative, take a signed integer, and optionally check in the function that the value is in range.

提交回复
热议问题