Is it possible to replace each if-else construct with an equivalent conditional expression?

(I have no serious need for this answer, I'm just curious.)

Is it possible to replace each if-else construct with an equivalent conditional expression using the conditional operator ?: ?

+7
c ++ c conditional-operator
source share
8 answers

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.

+10
source share

On its surface there. A conditional operator is an expression (i.e., it matters), and if / else is an operator (thus, it does not matter). They fulfill different "needs" in the syntax of the language.

However, since you can ignore the values โ€‹โ€‹of an expression, and since any expression can be converted to a statement by adding a semicolon, you can essentially emulate if / else with a conditional expression and two helper functions:

 // Original code: if (condition) { // block 1 } else { // block 2 } // conditional expression replacement: bool if_block() { // block 1 return true; } bool else_block() { // block 2 return true; } // Here the conditional expression. bool value discarded: condition ? if_block() : else_block(); 

However, having said this, I am not sure that this is anything more than curiosity ...

+4
source share

No, of course not. For the reasons already mentioned and much more!

 #include <cstdlib> #include <iostream> int main() { if(int i = std::rand() % 2) { std::cout << i << " is odd" << std::endl; } else { std::cout << i << " is even" << std::endl; } } 

Check where announced. This is not a commonly used method, but it can be used in situations like COM, where each call returns HRESULT, which (almost always) is zero on success (S_OK), non-zero on error, so you can write something like:

 if(HRESULT hr = myInterface->myMethod()) { _com_raise_error(hr); } 

A ternary operator cannot do anything similar.

+2
source share

The conditional operator expects both elements following ? , there will be rvalues โ€‹โ€‹(since the result of the conditional operator itself is an r-value) - therefore, although I am not a fully expert on C / C ++ standards, my intuition will be that the following will be forbidden (or, if it is not so, very bad coding style ...):

 (condition) ? return x : return y; 

whereas the if-else version will be quite standard:

 if(condition) return x; else return y; 

Now, if you said, can you take any program and write a similarly functioning program that would not use if-else? Of course available. This does not mean that it would be a good idea .;)

+1
source share

Using a conditional operator results in an expression, and both potential outcomes of the conditional operator must be "compatible" (convertible to the same type).

The if - else should not even โ€œreturnโ€ any type significantly smaller than one of the two branches.

+1
source share
 if( cond ) break; else a=b; 

can not always be replaced by an operator ?: . You can often (if not always) rethink all of your code to provide this replacement, but usually you cannot put anything that controls execution in ?: . break , return , loops, throw , etc.

+1
source share

I guess, yes:

 if (A) B; else C 

becomes

 try { A ? throw TrueResult() : throw FalseResult(); // or: throw A ? TrueResult() : FalseResult(); } catch (TrueResult) { B; } catch (FalseResult) { C; } 

Compared to procedures that are more natural, this allows break , continue , return , etc. A score of A required that does not end with TrueResult / FalseResult , but if you use these exceptions only to simulate if , this will not be a problem.

+1
source share

GCC has a statement expression , using it, you can rewrite if in equivalent expressions ?: ::

 if (<expression>) <statement1> else <statement2> 

EDIT: A void cast has two goals. The subexpressions in ?: Must be of the same type, and without a void cast, the compiler can print warning: statement with no effect .

 (<expression>)? (void)({<statement1>}) : (void)({<statement2>}); 
0
source share

All Articles