Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a reasonable use of the ternary operator? [closed]

Tags:

c++

c

c#

ternary

Are there any understanding / maintainability issues that result from code like

inVar1 == 0 ? NULL : v.push_back(inVar1);
inVar2 == 0 ? NULL : v.push_back(inVar2);

and so forth.

The possibly confusing idea is using the ternary operator for program flow rather than variable assignment, which is the usual explanation.

I haven't seen coding standards at work that address this usage, so while I'm comfortable doing this I'd like to find out if there is a good reason not to.

like image 508
user63572 Avatar asked Feb 07 '09 01:02

user63572


People also ask

Is it good practice to use ternary operator?

It's a good practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you should avoid using the ternary operators.

When should ternary operator be used?

Programmers use the ternary operator for decision making in place of longer if and else conditional statements. The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison.

How do I check my ternary operator condition?

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.

Which is an example of a ternary operator?

Example: C Ternary Operatorprintf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.


2 Answers

I think it's confusing and a lot harder to read than simply typing;

if (inVar != 0)
  v.push_back(inVar);

I had to scan your example several times to figure out what the result would be with any certainty. I'd even prefer a single-line if() {} statement than your example - and I hate single-line if statements :)

like image 165
Andrew Grant Avatar answered Sep 18 '22 16:09

Andrew Grant


The ternary operator is meant to return a value.

IMO, it should not mutate state, and the return value should be used.

In the other case, use if statements. If statements are meant to execute code blocs.

like image 23
thinkbeforecoding Avatar answered Sep 20 '22 16:09

thinkbeforecoding