overflow – Unsigned integer underflow optimization
I’m having some problem with the following issue:
#include <iostream>
using namespace std;
int main()
{
uint8_t l = 200, r = 2, c = 199;
bool res1 = (l - c) < (r - c);
bool res2 = uint8_t(l - c) < uint8_t(r - c);
uint8_t ll = l - c;
uint8_t rr = r - c;
bool res3 = ll < rr;
std::cout << std::boolalpha << res1 << std::endl;
std::cout << std::boolalpha << res2 << std::endl;
std::cout << std::boolalpha << res3 << std::endl;
return 0;
}
Compiling int with g++ and clang++ I got
false
true
true
Now the whole point is that I would like to exploit the unsigned underflow , i.e. I expect the second and third answer. I imagine that in the first case, the compiler elide on both side c
. I would like to know whether there is a robust and compiler-independent way to handle this (without explicitly checking for underflow, which can lower the performance).
Read more here: Source link