0

I'm having some problem with the following issue in c++:

#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).

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
MaPo
  • 613
  • 4
  • 9
  • Remember that integer promotion happens in expressions _"... In particular, arithmetic operators do not accept types smaller than int as arguments.."_ see https://en.cppreference.com/w/cpp/language/implicit_conversion – Richard Critten Dec 03 '21 at 09:01
  • Thank you. But I still do not see why there is difference between `res2` and `res3`. – MaPo Dec 03 '21 at 09:08
  • But there is no difference between `res2` and `res3`. Live example showing the intermediate results - https://godbolt.org/z/dz1fvoeax – Richard Critten Dec 03 '21 at 09:40

0 Answers0