c - if + else if + else in one line?

Viewed 51004

I just got a question idea after having misunderstood a friend's statement.

My friend told me: I just taught a colleague how to do a if/else in one line in c.

Example:

int i = 0;
i < 0 ? printf("i is below 0") : printf("i is over or equal to 0");

For now, nothing new, it's called a ternary and most people know about that kind of statement BUT I first understood that:

I just taught a colleague how to do a IF / ELSE IF / ELSE in one line. Since I don't / didn't know that doing such a thing is possible I tried to do something like

int i = 0;
 i < 0 ? printf("i is below 0") : i == 0 ? printf("i equal 0") : printf("i is over 0");

Is it actually possible to do a if / else if / else "ternary". Or is there a way to do such a thing without having an horrible piece of code?

3 Answers

If you see e.g. this conditional expression reference you can see that the format of a "ternary expression" is

condition ? expression-true : expression-false

All three parts of the conditional expressions are, in turn, expressions. That means you can have almost any kind of expression, including nested conditional (ternary) expressions in them.


It should be noted that conditional expressions might make the code harder to read and understand, especially if used badly or if one attempt to put too much logic and nesting into the expressions.

This is definitely valid.

Or you could try something like this -

printf(i < 0 ? "i is below 0" : i == 0 ? "i equal 0" : "i is over 0");

C has both statements and expressions. There are two different kinds of syntactical things. BTW lines don't matter much in C (except for the preprocessor).

Expressions (like f(1,x+y) or even x=y++) are a special kind of statements (the most common one).

As an extension to C, the GCC compiler adds statement expressions, beyond what the C11 standard (read n1570) defines. Please download then read that n1570 repoort.

if is for conditional statements but the ternary ?: operator is for expressions (with all three operands being sub-expressions).

Some programming languages (notably Lisp, Haskell, Scheme, Ocaml) have only expressions and don't have any statements.

Related