Cjdcoy Cjdcoy - 8 months ago 73
C Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download