Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to write a if then else type statement

Tags:

c++

c

Let's say I have a criteria and I want to add a delta if that criteria is true, and do the opposite (subtract) if it is false.

bool bBoolean;
int iDelta;
int iQuantity;

Is there a more concise and elegant way to write that piece of code ? I mean without repeating the keywords iQuantity and iDelta.

if(bBoolean)
  iQuantity -= iDelta;
else 
  iQuantity += iDelta;
like image 865
Michel Hua Avatar asked Jun 04 '26 01:06

Michel Hua


2 Answers

The shortest thing I can think of is:

iQuantity += (bBoolean) ? -iDelta : iDelta;

Edit: This is commonly called a ternary statement, though it's proper name (what it's called in the standard) is "conditional expression" or "conditional operator".

(Thanks to Rune for the official name.)

like image 131
Corbin Avatar answered Jun 06 '26 05:06

Corbin


This is the ternary operator. It is frowned upon by some for its potential to be less clear than if...else. I like it, but try to be careful.

int sign = criteria ? -1 : 1;
quantity += (delta * sign);
like image 39
Peter Wood Avatar answered Jun 06 '26 05:06

Peter Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!