Integer overflow in C: standards and compilers

前端 未结 7 1116
予麋鹿
予麋鹿 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 12:41

    In C99 the general behavior is desribed in 6.5/5

    If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

    The behavior of unsigned types is described in 6.2.5/9, which basically states that operations on unsigned types never lead to exceptional condition

    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.

    GCC compiler has a special option -ftrapv, which is intended to catch run-time overflow of signed integer operations.

提交回复
热议问题