detecting multiplication of uint64_t integers overflow with C

前端 未结 5 1157
天涯浪人
天涯浪人 2021-02-07 08:11

Is there any efficient and portable way to check when multiplication operations with int64_t or uint64_t operands overflow in C?

For instance, for addition of uint64_t I

5条回答
  •  情书的邮戳
    2021-02-07 08:35

    Actually, the same principle can be used for multiplication:

    uint64_t a;
    uint64_t b;
    ...
    if (b != 0 && a > UINT64_MAX / b) { // if you multiply by b, you get: a * b > UINT64_MAX
        < error >
    }
    uint64_t c = a * b;
    

    For signed integers similar can be done, you'd probably need a case for each combination of signs.

提交回复
热议问题