return (a<b?a:b);

What does the below line of code mean? Explain by examples.
What is this process called?

 
  return (a<b?a:b);
i think that if a< b then return a ;
else if a>b return b;
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;
It's called 'conditional operator' or 'ternary operator':

http://www.cplusplus.com/doc/tutorial/operators/
http://en.wikipedia.org/wiki/%3F:
So, if a==b then it will return the second value which is b?
Yes
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
Topic archived. No new replies allowed.