0

Assuming that all variables after the assignment operator are properly initialized, what would this multiple ternary operator look like grouped together?

int x = m < n ? n < o ? o < p ? p : o : n : m;

Edit: This seems like a question of operator precedence with regards to multiple ternary syntax. Following examples provided in the link, I think grouping this statement should look like the following:

int x = (m < n ? (n < o ? (o < p ? p : o) : n) : m);

Where o < p ? p : o is executed first
Followed by n < o ? (...) : n
Followed by m < n ? (...) : m

Is this right?

ike5
  • 188
  • 1
  • 10
  • What happened when you tried supplying values for `m`, `n`, `o` and `p` and attempting to deduce the logic? What happened when you tried reading the documentation, specifically the part about operator precedence? What problem do you hope to solve by writing code this way? If you are being asked to analyze this for homework, please read https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions. But this kind of puzzle is generally off topic for Stack Overflow. – Karl Knechtel Jul 15 '21 at 00:06
  • This shouldn't need our help: add parentheses into that monstrosity, and you'll have your answer pretty much as part of that exercise. Start with `(o < p ? p : o)` and then work your way out, wrapping one more ternary each step. – Mike 'Pomax' Kamermans Jul 15 '21 at 00:09
  • i tried compile then decompile, but rediculously sometimes i got the original statement with some additional parentheses, sometimes i get 2 if else but still one ? statement. – Lei Yang Jul 15 '21 at 00:12
  • Thanks for the tip on grouping. This is the first time I'm seeing a ternary operation with more than three operands. This statement is part of a larger 1Z0-819 exercise on prefix and postfix operators, so I cleaned up the example in order to picture it. I tried tracing variable values, but the output wasn't as predicted. – ike5 Jul 15 '21 at 00:40

1 Answers1

2

The ? operator is defined like this: if "condition is true" then do the operator before :, else the thing after :. So it would look like this:

if (m < n){
    if(n < o){
       if(o < p){
           x = p;
       }
       else x = o;
    else x = n;
    }
else x = m;
yassadi
  • 524
  • 1
  • 9
  • 20