Why ternary operator does not support blocks?
For roughly the same reason that a bicycle does not support wings.
If you have two blocks of statements, and you want to execute one or the other based on a condition, there's a perfectly good way to do that: the if
/else
statement.
And if you have two expressions, and you want to evaluate one or the other based on a condition, that's what the ternary or ?:
operator is for.
But asking the ?:
operator to execute one or the other of two blocks of statements is asking it to do something it's not meant for. Continuing the jokey analogies, it's like asking, why can't a hammer drive screws?
This distinction — that if
/else
is for blocks of statements, and ?:
is for expressions — flows out of C's fundamental distinction between expressions and statements. They're only partially integrated in C: you can turn any expression into a statement by putting a semicolon after it, but you can not, in general, use a statement as an expression. Why not? Well, partly because the syntax of the language doesn't permit it, and partly because there's no universal definition of what the value of a statement (or a block of statements) is.
Now, you can certainly imagine a language in which every statement has a well-defined value. In such a language, if
/else
and ?:
would probably be fully interchangeable. And, in fact, some C compilers do implement this full integration of expressions and statements, as an extension — but it's an extension, not Standard C.
(i==1)?({printf("Hello\n");}:({printf("World\n");});
– Nogood