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

后端 未结 4 1305
温柔的废话
温柔的废话 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 04:58

    int a, b;
    b = abs(a); // will overflow if a = 0x80000000
    if (b < 0) printf("overflow");  // optimized away 
    

    (You seem to be assuming 2s complement... let's run with that)

    Who says abs(a) "overflows" if a has that binary pattern (more accurately, if a is INT_MIN)? The Linux man page for abs(int) says:

    Trying to take the absolute value of the most negative integer is not defined.

    Not defined doesn't necessarily mean overflow.

    So, your premise that b could ever be less than 0, and that's somehow a test for "overflow", is fundamentally flawed from the start. If you want to test, you can not do it on the result that may have undefined behaviour - do it before the operation instead!

    If you care about this, you can use C++'s user-defined types (i.e. classes) to implement your own set of tests around the operations you need (or find a library that already does that). The language does not need inbuilt support for this as it can be implemented equally efficiently in such a library, with the resulting semantics of use unchanged. That's fundamental power is one of the great things about C++.

提交回复
热议问题