I am a little behind right now, so this week’s post will be fairly short, and will also be a little bit reminiscent of something a high school Latin teacher would write. (Almost 2 years into full time programming, and I still think about Latin fairly often, and still miss my students.)
Anyway, today we’re going to explain unary, binary, and ternary. Every now and then I’ll be reading documentation and I’ll see a gem of a sentence about “ternary operators,” and I can’t help but think there’s a communication mismatch. When I imagine people reading through docs trying to figure out what a ? means in source code, I suspect that many of them do not find the phrase “ternary boolean operator” abundantly helpful. While we’re talking about ternary operators, we might as well cover unary operators and binary operators. Binary operators are extra confusing, because “binary” doesn’t seem to mean the same thing in the phrase “binary operator” that it means in phrases like “computers do math with binary numbers.”
In languages, we talk about different kinds of numbers. The usual ones are “cardinal numbers,” which are numbers we count with (one, two, three, etc. in English). Next most normal are “ordinal numbers,” which we use for putting things in order (first, second, third). There are also “distributive numbers,” which English doesn’t really have, but can be translated by phrases like, “one each”. In Latin, “binus” and “ternus” are distributive numbers for two and three.
So there’s a notion of “each” in “ternary operator”: Each ternary operator takes three operands. That’s what makes it ternary. Each binary operator takes two operands and, you guessed it, each unary operator takes on operand.
Let’s wrap up with some examples:
- unary operator `-` in some languages, if I have `int a`, I can write `int x = -a;`, which means the same thing as `int x = a * -1`. This is a unary operator because it has only one operand; it negates a single integer.
- Binary operator: this is most of them. `+` is a binary operator, because it takes two numbers and returns their sum.
- Ternary operator: The only one I know is the condition
? if_true_value : if_false_valuethat many languages have. It takes three operands (the condition, the value if the condition is true, and the value if the condition is false). The first value has to be a boolean, hence ternary boolean operator.
Personally, I’ve always found it easier to understand a term if I understand why it’s called what it is. Anyway, maybe now some documentation will be a little less mystifying, or maybe you’ll be able to help someone remember what the ternary boolean operator does.
Extra credit: here’s an old Latin grammar on Google Books
Till next week, happy learning!