Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

For example, would you prefer this one-liner

int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

share|improve this question

closed as not constructive by gnat, Walter, Thomas Owens Nov 26 '12 at 16:39

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

This particular use of it is :) –  karmajunkie Dec 20 '10 at 16:48
I prefer questions like this to end with "considered harmful?" rather than "evil?" It's sort of a time-honored tradition in programming. –  Jesse C. Slicer Dec 20 '10 at 19:13
Post the if/else solution and see the difference and judge for your self –  OscarRyz Dec 20 '10 at 19:30
Who coded that, and what does their version of a median for four numbers look like? Or five? –  Mason Wheeler Dec 20 '10 at 21:56
I will summon Paracelso and his "Nothing is poision and everything is poison, the difference is in the dose" here. Your example is a perfect case of a poisonous dose. –  Konamiman Nov 26 '12 at 8:50
show 15 more comments

33 Answers 33

It's also necessary for const

const int nLegs  = isChicken ? 2: 4 ;
share|improve this answer
show 3 more comments
return (a + b + c) - max(a, b, c) - min(a, b, c); 

I was going to try to do this using ternary but figured that if you could get the max and low with ternaries than you would by definition know the median

I know this doesn't answer the question, I just thought of it and wanted to share

share|improve this answer
add comment

As others said, its a blessing, but I always use parenthesis to read expressions easier:

a = (x == y)?(
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.