What should happen to the negation of a size_t (i.e. `-sizeof(struct foo)`))?

后端 未结 6 465
[愿得一人]
[愿得一人] 2020-12-06 17:39

I\'m dealing with some code at work that includes an expression of the form

-(sizeof(struct foo))

i.e. the negation of a size_t

6条回答
  •  青春惊慌失措
    2020-12-06 18:05

    Both ISO C and ISO C++ standards guarantee that unsigned arithmetic is modulo 2n - i.e., for any overflow or underflow, it "wraps around". For ISO C++, this is 3.9.1[basic.fundamental]/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.41

    ...

    41) 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.

    For ISO C(99), it is 6.2.5/9:

    A computation involving unsigned operands can never 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 type.

    Which means the result is guaranteed to be the same as SIZE_MAX - (sizeof(struct foo)) + 1.


    In ISO 14882:2003 5.3.1.7:

    [...] The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the pro- moted operand. The type of the result is the type of the promoted operand.

提交回复
热议问题