Kindly give an detailed explanation too. How does it work ?
Asked
Active
Viewed 6,436 times
3 Answers
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
-
Can i get examples with numbers instead ? Like how to find the smallest numberr among two numbers please. – 912M0FR34K Jan 25 '12 at 09:52
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
-
That's a potentially very bad macro. Multiple evaluations of a and b. – David Heffernan Jan 25 '12 at 11:57
-
@DavidHeffernan: I don't know why did you say that, but you can have a look to the [link](http://stackoverflow.com/questions/2458723/c-macro-for-minimum-of-two-numbers) – Rasmi Ranjan Nayak Jan 25 '12 at 12:01
-