x = something ? foo() : bar();
x = something ? foo() : bar();
Since functions also have a block, and the return value of the function is the result of the block, this is much more consistent.
Funny story; years before I became a C programmer, and at a time when I didn't yet study ISO C properly, I discovered and used this extension naturally.
I wanted to evaluate some statements where only an expression could be used so I thought, gee, come on, can't you just put parens around it to turn it into an expression and get the value of the last expression as a return value? I tried that and it worked. And of course, if it works it's good (standards? what are those?)
Then I tried using the code with a different C compiler; oops!
Anyway, this GNU C feature doesn't have as much of an impact as you might think.
x = if(something) { a = foo(); baz(a); } else { b = bar(); baz(b); }
some_condition ? this : that
some_condition? then this, otherwise thatTyping this, I realize how hard it is to explain without speaking it :)
It's a little tricky, because in the above, the `if` keyword appears after the question mark.
Is the color red? Yes-- this: no-- that.
Trying to make a parsimonious English sentence while maintaining the syntax elements : P
Just read it as:
IF some_condition THEN this ELSE that x = baz(if (something) foo() else bar())x = something ? ((a=foo()), baz(a)) : ((b = bar()), baz(b));
Otherwise:
x = something ? baz(foo()) : baz(bar());
x = (something) ? ({ a = foo(); baz(a) }) : ({ b = bar(); baz(b); });
However, since all your forms are actually expression statements, we can happily just use the ISO C comma operator: x = (something) ? (a = foo(), baz(a)) : (b = bar(); baz(b));
If C provided operators for iteration, selection and for binding some variables over a scope (that scope consisting of an expression), everything would be cool. E.g. fantasy while loop: x = (< y 0) ?? y++ : y; // evaluate y++ while (< y 0), then yield y.
Variable binding: x = let (int x = 3, double y = 3.0) : (x++, x*y);
The problem is that some things can only be done with statements.The ternary operator is not actually lacking anything; with the comma operator, multiple expressions can be evaluated. What's lacking is the vocabulary of what those expressions can do.