If-statements are the wild west. Who knows what an if statement will do? An if-statement may be as simple as a ternary, or it might be a branch point and the resulting logic streams will never meet again.
And thanks to the preprocessor, any identifier could potentially be calling a function.
There’s the condition (evaluated first), the true case and the false case. Only one of the cases is evaluated.
I’m assuming you were alluding to some sort of “x++ = x++ * *x++” style situation, but the ternary expression isn’t a statement and there are sequence points in between. As a bonus, the first result for “ternary operator evaluation order” gave me someone who linked to the standard [1]. Quoting from the standard that they quoted:
> The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand(whichever is evaluated), converted to the type described below.
[1] https://stackoverflow.com/questions/65109494/order-of-evalua...
My point was that since ternaries can call functions, and functions can have side effects on global state, the concept of an "if" being a "statement" vs a ternary being an "expression / value" is not nearly as meaningful as it's made out to be. A ternary can trade stocks, fire a 500W laser, unlock a velociraptor enclosure, etc, just as easily as an if can.
We can objectively say that ternaries are shorter and simpler however. (Simpler because they can do fewer things than an if-statement or if-expression.)
So, you can do (untested)
foo = bar ? ({a=1;b=2;}) : ({a=2;b=1;});
That’s widely supported in other compilers for compatibility reasons (https://stackoverflow.com/questions/6440021/compiler-support...)
You can also (mis)use the comma operator like this (again untested):
foo = bar ? f(),g() : g(),f();
but that is more limited.In a more serious tone, ternaries in places where they should be used, i.e. as expressions, are in my opinion much clearer to read than replacing them with an if-else statement. In my mind, an if/else block is an imperative entity that describes two different actions that could happen. Even if in reality both branches are trivial, my mind will be unnecessarily occupied with the fact that it needs to reason about code here, not just data. A ternary, on the other hand, is a declarative entity, saying that this expression takes on this or that value, usually in such a way that each branch of it maintains some invariant with respect to what's in the conditional.
That's true in some languages. But in some languages if-else can also be used as in expression. e.g. in Rust I can write:
let foo = if condition { "FOO" } else { "BAR" }So many languages use clear words like "if" and "then" and "else" and parens and curly braces for conditional statements...
But then they go full Perl and mash their faces against the keyboard when developing syntax for conditional expressions.
It's bone-headed language-design that C did wrong and everybody else continues to do wrong because C.
myvar = condition_1 ? value_1
: condition_2 ? value_2
: condition_3 ? value_3
: value_fallback;Under what circumstances would that happen? I've never encountered a nested ternary that wouldn't be better replaced with readable code, so now I'm wondering what experiences I've been missing. :)
myvar = if(condition_1) {value_1}
else if(condition_2) {value_2}
else if(condition_3) {value_3}
else {value_fallback}; #define TERN(c, a, b) c ? a : b
I'm not a fan of ternaries, but that macro makes it kind of more ligible. #define TERN(c, a, b) ((c) ? (a) : (b))As Liquid_Fire points out, it's also probably incorrect.
Here's a concrete example:
const int min = x < y ? x : y;
int min;
if (x < y)
min = x;
else
min = y;
Note also that this prevents variable min from being made const, unless you are using c++ and wrap the entire if/else in an immediately invoked lambda, which of course would require additional verbosity.-- example:
var x;
if(this)
x = 10;
else
x = 11;
-- is uglier than:
var x = this ? 10 : 11;
int x = (cond)
? 5
: 1; int x = (cond) ?
5 :
1;
Since the question mark applies to the condition and not the 5. This also highlights the 2 possiblities of the value in a more clear way. The two possible values are directly stacked with nothing in front of them. printf(condition? "YES": "NO");
than something like if (condition) {
printf("YES")
} else {
printf("NO")
}In that apples-to-apples comparison, it's really a toss up which is more readable. Looking at the if statement, anyone who has been reading code for any amount of time is going to immediately recognize the pattern. There's no "scanning two sides".
I usually just transform functions with 2+ if statements into functions without `if` statements by extracting `if` statements into other smaller functions where I can write it with an early return.
Looks great.
But expressions can contain blocks. Therefore, this is valid:
int main(void) {
while (1) {
1 ? ({ break; }) : ({ break; });
}
}
The right way to easily spot control flow construct is syntax highlighting.