0

I recently came across a ternary logic statement in this form:

condition, condition ? condition ? expr1 : expr2 : expr3

I am not sure how to interpret this. I am not seeing anything on the web. Anybody got any info on this.

8
  • 5
    Hunt down whomever wrote that and play the worst 90s pop music at them until they learn to use if/else. Commented Jan 8, 2018 at 17:58
  • This is only a point of view @Quentin, it's not so hard to read, by the way, if/else can be unreadable. Commented Jan 8, 2018 at 18:07
  • @leaf except that the comma operator makes it completely ambiguous as to what original author intent was Commented Jan 8, 2018 at 18:10
  • @charlietfl There are many ambiguous stuffs when you learn programming. Commented Jan 8, 2018 at 18:11
  • @charlietfl And the comma is not part of the ternary expression :-) Commented Jan 8, 2018 at 18:16

2 Answers 2

2
condition, condition ? condition ? expr1 : expr2 : expr3

First you have a comma operator. This evaluates as the right hand side. So the first condition does nothing.


condition ? condition ? expr1 : expr2 : expr3

Then you just have two ternary expressions

It is the same as:

condition ? (condition ? expr1 : expr2) : expr3

So if the first condition is false, you get expr3.

Otherwise, the second condition picks between expr1 and expr2.


Never write code like this! Concisenes is only a virtue to the point where it makes it hard to understand what code means.

Sign up to request clarification or add additional context in comments.

Comments

1

Let's try:)

condition1, condition2 ? condition3 ? expr1 : expr2 : expr3

condition1 don't parse. Let's use 'return' for example.

if( condition2 ){
  if(condition3){ 
      return exp1;
  } else { 
      return expr2;
  }
} else {
  return expr3;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.