Alex Rivera | Logout

How do I use the conditional (ternary) operator?

Asked 2008-12-25T16:27:10.653
46

I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language.

I think it works something like: (Pseudo code)

If A > B
   C = A
Else
   C = B

How can I achieve this?

Edit
Report

1 Answer

1

I would say the ? is a short-cut. However, some "hard-core" programmers tend to say write it out the long way so in future cases, people can easily read and modify code.

For example, if you write

int a = b<c ? b : c;

Some people claim that it's clearer to write:

if(b<c)
 a = b;
else
 a = c;

Because in future cases, people can catch it. Of course, a simple b<c ? b:c is easy to catch, but sometimes complex operations are put in and it can be hard to spot.

answered 2010-05-06T18:29:30.467

Your Answer