How to make it so that when subtracting 2 numbers uint32_t , when we subtract more from the smaller one, the result is 0?

Without if, and preferably without comparison operators

  • Write the result in a bezankokvy type. - BlackOverlord
  • he is unsigned. needs to be done so that CF does not touch - neko69

3 answers 3

"Well, the tasks you, sir, put ..." (c) C / f "Formula of love"

There is one catch - a sign shift is required, and so that it works correctly, spreading the sign. The trouble is that formally it is implementation defined, although in most implementations it works correctly.

If so, then you can implement the desired "monus", it is also dozu(x,y) you can:

 (xy)&~(int((~x&y)|((~(x^y))&(xy)))>>31) 

Read Warren G. Algorithmic tricks for programmers , the book is worth it :)

     u32b sat_subu32b(u32b x, u32b y) { u32b res = x - y; res &= -(res <= x); return res; } 

    Peeped here .

      The simplest solution would be the following:

       auto sum = first > second ? first - second : 0; 

      There are no ifs, but there is an "undesirable" comparison operator. Well, it is undesirable, but not prohibited.

      You can make another solution to meet the requirements:

       bool div = first / second; auto sum = (first - second)*div; 

      No ifs, no comparisons. The decision is terrible. Like the requirements.

      • @ aleks.andr, this is not true, my code will give 8, in your example. - ixSci
      • Hmm, bool'omagy ... - Qwertiy
      • The ternary operator is abbreviated if, I think that’s not what the author wanted. - iksuy
      • one
        @iksuy, a ternary operator is a ternary operator. And in the task it is clearly stated - it is impossible if, if I have not. - ixSci