Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator without else in C

I want to use ternary operator without else in C. How do I do it.

(a)? b: nothing; 

something like this. What do I use in nothing part?

like image 637
user437777 Avatar asked Sep 04 '12 09:09

user437777


People also ask

Can we write ternary operator without else?

You cannot use ternary without else, but you can use Java 8 Optional class: Optional.

Is there ternary operator in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

How many ternary operators does C have?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.

How do you use only if ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


2 Answers

If you are using a ternary operator like that, presumably it could be replaced by:

if (a) { b; } 

which is much, much better. (The intent is clearer, so the code is easier to read, and there will be no performance loss.)

However, if you are using the ternary operator as an expression, i.e.

printf("%d cat%s", number_of_cats, number_of_cats != 1 ? "s" : <nothing>);  a = b*c + (d == 0 ? 1 : <nothing>); 

then the <nothing> value depends on the context it is being used in. In my first example, <nothing> should be "", and in the second it should be 0.

like image 163
huon Avatar answered Sep 17 '22 16:09

huon


An omitted false expression is invalid. Try reversing the condition instead.

(!a) ?: b; 
like image 20
GOSteen Avatar answered Sep 16 '22 16:09

GOSteen