Integer overflow in C: standards and compilers

前端 未结 7 1118
予麋鹿
予麋鹿 2020-12-01 11:56

Edited to include proper standard reference thanks to Carl Norum.

The C standard states

If an exceptional condition occurs d

相关标签:
7条回答
  • 2020-12-01 13:01

    The previous postings all commented on the C99 standard, but in fact this guarantee was already available earlier.

    The 5th paragraph of Section 6.1.2.5 Types

    of the C89 standard states

    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 unsigned integer type.

    Note that this allows C programmers to replace all unsigned divisions by some constant to be replaced by a multiplication with the inverse element of the ring formed by C's modulo 2^N interval arithmetic.

    And this can be done without any "correction" as it would be necessary by approximating the division with a fixed-point multiplication with the reciprocal value.

    Instead, the Extended Euclidian Algorithm can be used to find the inverse Element and use it as the multiplier. (Of course, for the sake of staying portable, bitwise AND operations should also be applied in order to ensure the results have the same bit widths.)

    It may be worthwhile to comment that most C compilers already implement this as an optimization. However, such optimizations are not guaranteed, and therefore it might still be interesting for programmers to perform such optimizations manually in situations where speed matters, but the capabilities of the C optimizer are either unknown or particularly weak.

    And as a final remark, the reason for why trying to do so at all: The machine-level instructions for multiplication are typically much faster than those for division, especially on high-performance CPUs.

    0 讨论(0)
提交回复
热议问题