angrytoad
angrytoad

Reputation: 11

Unsure about these operators being used in this way

This code example comes from http://www.cplusplus.com/doc/tutorial/templates/ :

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}

What I am confused about is the "a>b?a:b" section part of the code which is being returned. Can somebody help me to understand what is going on here? Thanks.

Upvotes: 0

Views: 52

Answers (2)

maditya
maditya

Reputation: 8906

It's known as the ternary operator:

http://www.cplusplus.com/articles/1AUq5Di1/

You can think of return (a > b) ? a : b; as:

if(a>b) {
  return a;
} else {
  return b;
}

Keep in mind that the ternary operator actually produces a value, which is either a or b (which is why it works in the return statement).

So you can do things like

myType c = (a>b) ? a : b, which is roughly equivalent to

myType c;
if(a > b) {
  c = a;
} else {
  c = b;
}

Upvotes: 1

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14323

This is the ternary operator. It evaluates the expression before the ?, and if it's true, the value before the : is returned. Otherwise, the value after the : is returned.

It is basically a concise way of expressing the following if/else statement:

if ( a>b)
{
    return a;
}
else
{
    return b;
}

Upvotes: 1

Related Questions