問題描述
為什麼“如果”不是C中的表達式 (Why isn't "if" an expression in C)
What is the reason for 'if' statements in C not to be expressions? Why was the ternary operator added to C instead of 'if' expressions?
Are there technical reasons or is it just a historical decision?
Ed.: to make things more clear, I've imagined an 'if' expression like this: if its result is not used, it may behave just like a statement, but if something requires the result, it must have the else
branch of the same return type.
Now I see that the result is ambiguous: indeed, it's a weird hybrid of expression and statement, so the clear separation is better.
‑‑‑‑‑
參考解法
方法 1:
I would say because C is an imperative language, modeling machines, not maths, where all functions have a value.
An if‑expression needs a mandatory else‑expression (or a mandatory exception‑throw), which does not fit nicely in a performance‑ and machine‑oriented programming language in which you only pay for what you use.
(sidenote) The standard could state that if the if‑expression is not on the right hand side of an assignment, that the else part becomes optional. That, however, would make the C grammar more complex.
A second restriction: Within an expression, you can only use other expressions. You can't for example:
int i = if (foo) { for (int x=4; x; ‑‑x) {}; 42 } else bar;
While in principle possible, I think that would take away some of C's beautiful, minimalistic grammar; you would have to extend the rules for trivial expressions vs. code blocks, you need to remember more context while parsing, and so on. (/sidenote)
The ternary operator in C++ (note: C++) does exactly that: Requiring an else‑part because it is an expression or throwing an exception:
int foo = frob ? bar : throw "crap";
That thing is basically an if‑else‑expression; Python would be an example for a language that replaced ?:
with if/else
:
foo = frob if bar else 42
What you describe is really two things: If‑statements and if‑expression. Both are in C; both have distinct features. And, somehow, you ask why not both if‑statements and if‑expressions are expressions.
方法 2:
An if is defined with something like that:
"if" <whitespace> "(" <whitespace> <expression> <whitespace> ")" <whitespace> <statement>
So it will accept a statement if the condition is met. If it was an expression it would need to return something, hence it would only be able to execute other expressions rather than general statements. In fact the ?: can only execute conditional expressions but not statements.
(by Dmytro Sirenko、Sebastian Mach、LtWorf)