-4

Kindly give an detailed explanation too. How does it work ?

skaffman
  • 398,947
  • 96
  • 818
  • 769
912M0FR34K
  • 121
  • 1
  • 3
  • 11

3 Answers3

3
return a<b ? a : b

is equivalent to

if (a<b)
    return a;
else
    return b;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • +1 - beat me too it. Slow update times today. – ChrisBD Jan 25 '12 at 09:50
  • Can i get examples with numbers instead ? Like how to find the smallest number among two numbers please. – 912M0FR34K Jan 25 '12 at 09:54
  • I don't understand. `a` and `b` can be whatever you want. They can be numbers. If you mean how do you use conditional operator to find the minimum of literals like `6` and `9` say then that's pointless. You can do it by inspection. Also, if you have specific questions to ask, don't add them in comments, instead edit the question. – David Heffernan Jan 25 '12 at 09:56
1

The conditional operator ? : works in a similar manner to if else.

So:

int A;
int B;
// some code that sets the values of A and B
return A>B?B:A

Is the same as

int A;
int B; 
    // some code that sets the values of A and B   
if A>B
    return B;
else
    return A;

An explanation of the conditional operator:

`<Perform operation that gives a boolean result>` ? <return this answer if true> : <return this answer if false>

So you could have:

int smallestValue;
int inputA;
int inputB;

//some code that sets the value of inputA and inputB - perhaps from console input

smallestValue = (inputA < inputB) ? inputA : inputB;
ChrisBD
  • 9,104
  • 3
  • 22
  • 35
0

It's a macro does the same work...

#define min(a, b) a<b ? a : b
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122