0

this is a function.

int find(int x, int y){
    return( (x<y) ? 0 : (x-y) );
    }

when we execute find(x,find(x,y)) , it will give minimum of x and y. I'm not getting how this is executing to give the minimum. what does "( (x<y) ? 0 : (x-y) ) ." means in C++?

lurker
  • 56,987
  • 9
  • 69
  • 103
Mahi786
  • 9
  • 1
  • 2
  • 2
    It's a ternary expression with the conditional operator. – Andrew Li Jan 07 '20 at 23:41
  • Shorthand for `if (x – tshimkus Jan 07 '20 at 23:43
  • *when we execute `find(x,find(x,y))` , it will give minimum of `x` and `y`.* Actually, it doesn't. `find(-1, find(-1, 1))` gives 0. It only works for non-negative `x` and `y`. – lurker Jan 07 '20 at 23:54
  • Does this answer your question? [How do I use the conditional (ternary) operator?](https://stackoverflow.com/questions/392932/how-do-i-use-the-conditional-ternary-operator) – Moia Sep 03 '21 at 09:19

1 Answers1

0

Very interesting code to find a minimum and it works!

The only restriction, numbers must be positive!

The meaning is simple: when x < y we return 0, otherwise we return x - y.

Now, consider all possible cases with 0 < x, y:

x < y:

    find(x, find(x,y)) == find(x, 0) == x - 0 == x == min(x, y)

x == y:

    find(x, find(x,y)) == find(x, x - y) == find(x, 0) == x - 0 == x == min(x, y)

x > y:

    find(x, find(x,y)) == find(x, x - y) == x - (x - y) == y == min(x, y)

With negative numbers it does not work.

Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
  • 1
    It works for cases x, y >= 0. So it works for non-negative numbers. – lurker Jan 08 '20 at 00:06
  • agree, but the proof will require more entries :-) the main point, it does not work for nagatives – Anatoliy R Jan 08 '20 at 00:08
  • Your examples you say "with negative numbers it does not work". 0 isn't negative and it works in your examples. So you did cover it. It doesn't require more entries. "numbers must be positive" simply isn't true. :) – lurker Jan 08 '20 at 00:12
  • Well... agree. BTW we can extend it to negatives: the expression returns minimum of this union set: {0 U {x, y > 0}} (zero positive part of x, y) :-) – Anatoliy R Jan 08 '20 at 00:27