It’s fitting that the one thing that seems to generate the most C code questions is a single character: ? — the question mark.
This is C’s ternary operator. Or as I like to call it, the Altoids operator, as it packs a lot of flavor into a tiny package.
Consider the following code:
if (condition) { a = 42; } else { a = 17; }
The ternary operator provides a shorthand for this construct, packing a conditional test, if/else and assignment into a single line:
a = condition ? 42 : 17;
“condition
,” again, is a placeholder. This is not real code. An actual program would have a meaningful thing to test there.
If the condition evaluates as true
, the first value (left of the colon) is used. If false, the second value (after colon) is used.
While this if/else/assign pattern doesn’t come up a whole lot, it’s used just enough that you can easily imagine how veteran programmers, who may have grown up on a single fixed 80x25 character screen, would love something so nutrient-dense.
The downside is that, on its own, it’s kind of nonsensical. Other C keywords like do
, while
, if
and else
provide at least some vague indication of what they do. But ?
is like they’d used up every last character on the keyboard for something else and it came down to this. I guess you could say it’s a condition phrased like a question.
It’s not just for A/B assignment. You can wrap this up in a conditional statement (e.g. while
), or put function calls on one or both sides of the colon:
while (value ? func1() : func2()) { // Body of loop }
Much as I appreciate its density, it’s only right to avoid inflicting this on those just starting out, that would be mean. You’ll never see this in NeoPixel strandtest.
But to seasoned coders, it’s expressing a complex idea in a small space. Deep down inside libraries I’ll use it all over the place, but that’s basically the code equivalent of at-home in a bathrobe.
And for projects aimed at intermediate coders? Love to put one or two in there just to make them ask questions.
Text editor powered by tinymce.