No useful and reliable way to detect integer overflow in C/C++?

后端 未结 4 1255
温柔的废话
温柔的废话 2021-02-08 04:47

No, this is not a duplicate of How to detect integer overflow?. The issue is the same but the question is different.


The gcc compiler can optimize away an

4条回答
  •  醉梦人生
    2021-02-08 05:17

    Just use the correct type for b:

    int a;
    unsigned b = a;
    if (b == (unsigned)INT_MIN) printf("overflow");  // never optimized away
    else b = abs(a);
    

    Edit: Test for overflow in C can be safely done with the unsigned type. Unsigned types just wrap around on arithmetic and signed types are safely converted to them. So you can do any test on them that you like. On modern processors this conversion is usually just a reinterpretation of a register or so, so it comes for no runtime cost.

提交回复
热议问题