return (a<b?a:b);

Jul 16, 2013 at 3:06pm
What does the below line of code mean? Explain by examples.
What is this process called?

 
  return (a<b?a:b);
Jul 16, 2013 at 3:10pm
i think that if a< b then return a ;
else if a>b return b;
Jul 16, 2013 at 3:16pm
flussadl is correct (mostly -- it will also return b if a==b)

The ?: operator works as follows:

condition ? value_if_true : value_if_false

so return (a<b ? a : b);
could be rewritten as:

1
2
3
4
if(a < b)
    return a;
else
    return b;
Jul 16, 2013 at 3:20pm
It's called 'conditional operator' or 'ternary operator':

http://www.cplusplus.com/doc/tutorial/operators/
http://en.wikipedia.org/wiki/%3F:
Jul 16, 2013 at 3:23pm
So, if a==b then it will return the second value which is b?
Jul 16, 2013 at 3:29pm
Yes
Jul 16, 2013 at 4:56pm
What it does is evaluate the conditional statement. If that statement is true, it returns the value before the colon, a in this case. If it is false it returns the value after. Since the condition is a<b then a==b would be false and it would return b.

Edit: Ok, maybe "return" isn't exactly the right term for the statement. I guess it'd be more correct to say the statement evaluate to true/false. :)
Last edited on Jul 16, 2013 at 4:57pm
Topic archived. No new replies allowed.