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?
You cannot use ternary without else, but you can use Java 8 Optional class: Optional.
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");
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.
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.
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
.
An omitted false expression is invalid. Try reversing the condition instead.
(!a) ?: b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With