Is it possible to replace any if-else constructs with an equivalent conditional expression using the conditional operator?
No, you asked for it back. if / else "bodies" contain statements, and it is impossible to turn each expression into an expression , for example, try, while, break, as well as declarations. However, many โstatementsโ do mask expressions:
++i; blah = 42; some_method(a,b,c);
All these are instructions that consist of a single expression (increment, assign, function-call, respectively) and can be converted into expressions in a conditional expression.
So, cancel the question, as it sounds like you really want to know how equivalent the if / else expressions are to ternary conditional expressions: Is it possible to replace each conditional expression with equivalent if / else expressions? Almost everything, yes. A common example are return statements:
return cond ? t : f; // becomes: if (cond) return t; else return f;
But other expressions:
n = (cond ? t : f); // becomes: if (cond) n = t; else n = f;
What begins to indicate that conditional expressions cannot be easily replaced: initialization . Since you can only initialize an object once, you must break the initialization, which uses a conditional expression instead of an explicit temporary variable:
T obj (cond ? t : f); // becomes: SomeType temp; if (cond) temp = t; else temp = f; T obj (temp);
Note that this is much more tedious / cumbersome and requires something type-specific if SomeType cannot be configured by default and assigned.
Roger Pate
source share