Conditional operator in C

can each if ... then ... else statement be converted to an equivalent statement using only ?:

+4
source share
3 answers

Although any use I can think of for a ternary operator can be implemented as if / else, the opposite is not true; at least without resorting to perverse and meaningless "tricks" that do not bring any benefit in terms of performance, readability or maintainability.

If / else syntax:

if( <boolean expression> ) <statment>|<statment block> else <statment>|<statment block> 

whereas the syntax of the termar operator is ::

 <boolean expression> ? <expression> : <expression> ; 

The important thing is that <expression> and a <statement> are different syntax elements.

Very limited use of the form:

 if( b ) x = y else x = z ; 

can be implemented as:

 x = b ? y : x ; 

but the limitation here is that the same variable is assigned in both true and false sentences (and, therefore, both y and z are at least converted to type x). Therefore, we can say that any conditional assignment can be implemented using the ternary operator (in the end, this is its main purpose).

Now, since a function call is a valid expression, you can wrap true and false sentences in separate functions, but just prove that the point is somewhat perverse:

 if( b ) true_stuff() ; else false_stuff() ; 

is equivalent to:

 b ? true_stuff() : false_stuff() ; 

and these functions can contain any code at all.

So, in order to convert the more general case of if / else to the?: Operation, the true / false statements must first be wrapped by separate functions. However, even then, Neil Butterworth's examples will defeat this approach, since the behavior of break , continue and return affects the control flow outside the if / else structure (although perhaps these are also examples of code that you want to avoid!). Having a goto in if / else will also win this approach ..

I think in the end, even if you could, why would you want to?

+3
source

The code:

 if ( flag ) { exit(1); } else { return 0; } 

cannot be converted to:

 flag ? exit(1) : return 0; 

The best example would be inside a loop:

 if ( flag ) { continue; } else { break; } 

cannot be converted to:

 flag ? continue : break; 
+7
source

Not.

Both branches of the conditional expression must be evaluated with the same type, and this type must not be void .

For example, you can do this:

 x > 0 ? printf("Positive!\n") : 0; 

because printf returns int . (I would only use this in a round of golf, although, in fact, I just did .)

But you cannot do this:

 x > 0 ? exit() : 0; 

because exit returns void (or, in fact, doesn't return at all).

+1
source

Source: https://habr.com/ru/post/1305922/


All Articles