4 ms·
Because Java’s if does not return a value, you cannot say: return if (x < 0) "-" else "+"; This would have been a nice place to make an analogy to t
by jefftk 7y ago
Because Java’s if does not return a value,
you cannot say:
return if (x < 0) "-" else "+";
This would have been a nice place to make an analogy to the question mark operator, since a java programmer would probably be familiar with it and it allows you to write:
return if (x < 0) "-" else "+";
as
return x < 0 ? "-" : "+";
- felipemnoa 7y ago>>java programmer would probably be familiar with it And also C, C++, and Objective-C programmers. I'm sure there are more languages that use that operator that I have not mentioned here.
- scardine 7y agoI have not touched PHP in the last 10 years but if memory serves it also has the ternary operator. Ok, lets try it: $ php -a Interactive mode enabled php > echo 1 == 1 ? "foo" : "bar"; foo php > echo 1 == 2 ? "foo" : "bar"; bar Looks like javascript has it too: 1 == 1 ? "foo" : "bar" "foo" 1 == 2 ? "foo" : "bar" "bar"
- amenghra 7y agoBe careful, php’s ternary operator precedence is different from (most) other languages’ (consult binding direction). The use of parenthesis is highly encouraged...
- jefftk 7y agoSure, but the article is written with Java programmers in mind and doesn't mention any of the other languages.
- delinka 7y agoIt's called 'ternary operator' because it's `?` and `:` and takes three operands.
- jefftk 7y agoI don't like calling it the ternary operator because there are other ternary operators, like "x BETWEEN a AND b" in SQL. Sometimes it's called the "conditional operator" but my experience has been that "question mark operator" is what the most people will understand.
- delinka 7y agoIf you're going to reference other languages, `?` is an operator on its own in Swift. Calling `?:` by the name 'question mark operator' is only naming half of the thing.