return statement with '?' and ':'

Hi guys,

can someone explain to me the code below?
I have never seen this '?' and ':' like this in a return statement.

1
2
3
4
double tracer::anglefinder(double thetatarget, double currenttheta)
{
  return (thetatarget-currenttheta>0) ? thetatarget-currenttheta : pi2 + thetatarget-currenttheta ;
}


Best,
PIF
It's called the Ternary Operator. It's a short cut for
1
2
3
4
5
if (thetatarget - currenttheta > 0)
  return thetatarget - currenttheta;
else
  return pi2 + thetatarget - currenttheta;
}
Wow, that's cool.

Thank you for the fast reply!
This is a great post by @JLBorges displaying some examples of use:
http://www.cplusplus.com/forum/beginner/241094/#msg1072487

It's not demonstrated there, but the operator can also (obviously) be "chained", which looks like this:
1
2
3
4
5
6
7
8
9
return c1 ? a : 
       c2 ? b : 
       c3 ? c : d;

// And is read like
// if (c1) return a;
// else if (c2) return b;
// else if (c3) return c;
// else return d;  

closed account (E0p9LyTq)
? : is also known as the "conditional ternary operator" or the "conditional operator."

http://www.cplusplus.com/doc/tutorial/operators/
I see, so it is a very useful tool to keep the code short and readable.
The ternary operator is really capable of making the code concise and good-readable!
Note that "ternary operator" means an operator that takes three arguments,
similar to how "binary operator" means an operator that takes two arguments.

In C++, and many other languages, there are only one ternary operator (at least that I'm aware of) so there is generally no confusion but it explains why you mostly see it referred to as "conditional operator" in more formal texts.
Topic archived. No new replies allowed.