0

I am currently confused on what this syntax means. If i knew what it was called I would search for it but I saw it in a code and I have no idea what it means.

ptr = c < 0 ? ptr.left : ptr.right;

It is for traversing through an binary tree.

I am assuming that the first part c < 0 is a condition, and if its true, then ptr becomes ptr.left, and if it is false then ptr becomes ptr.right-

Or is it the other way around? I've never seen this before and would like some clarification. Thanks

Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28
seth
  • 1
  • 3
  • ok thx alot lolloo – seth Nov 04 '17 at 18:59
  • It is called a `ternary operator` https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html And, `ptr = c < 0 ? ptr.left : ptr.right;` is same as `if (c < 0) { ptr = ptr.left } else { ptr = ptr.right };` – isank-a Nov 04 '17 at 19:02
  • @Isank that documentation is surprisingly wrong: it is *a* ternary operator, but its correct name is the [*conditional operator*](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25). – Andy Turner Nov 04 '17 at 19:07
  • @AndyTurner - I would like to disagree because as far as I know conditional operators are `&& (AND)` and `|| (OR)` – isank-a Nov 04 '17 at 19:09
  • @Isank disagree all you like, that's the name in the language spec. If you look at the preceding sections of the spec, the names of the operators you are referring to are the "conditional-and" and "conditional-or" operators. – Andy Turner Nov 04 '17 at 19:11
  • @AndyTurner - The same JLS that you posted a link of says this `The ternary conditional operator ? : (§15.25)` too. – isank-a Nov 04 '17 at 19:24
  • @Isank in that context "ternary" is a qualifying adjective, in the same way that saying "the preceding sections" doesn't mean there's a type of section called a "preceding section". – Andy Turner Nov 04 '17 at 20:23
  • I agree with Andy Turner, ternary is just a qualifying adjective for an operator, meaning that it takes exactly three arguments. Similary, `&&` is a binary conditional operator, and `!` is an unary conditional operator. – Dorian Gray Nov 04 '17 at 21:00
  • PS: The operator in question is also called "Elvis operator" in less formal terms. :) – Dorian Gray Nov 04 '17 at 21:08

0 Answers0