简体   繁体   English

写一个if then else类型语句的简洁方法

[英]Concise way to write a if then else type statement

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. 假设我有一个标准,如果该条件为真,我想添加一个delta,如果为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. 我的意思是不重复关键字iQuantity和iDelta。

if(bBoolean)
  iQuantity -= iDelta;
else 
  iQuantity += iDelta;

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.) (感谢Rune的官方名称。)

This is the ternary operator. 这是三元运算符。 It is frowned upon by some for its potential to be less clear than if...else . 一些人不赞成它的潜力不如if...else I like it, but try to be careful. 我喜欢它,但要小心。

int sign = criteria ? -1 : 1;
quantity += (delta * sign);

iQuantity += (1-2*bBoolean)*iDelta;

在某些处理器上,额外算法比分支更快。

Why not: 为什么不:

int tmpDelta = iDelta;
if (iBoolean)
{
  tmpDelta = -tmpDelta;
}
iQuantity += tmpDelta;

To me, when I write or read code, I prefer to have something that as straight-forward as possible. 对我来说,当我编写或阅读代码时,我更愿意拥有尽可能直接的东西。 This says that the code will always update iQuantity , and that the update will be inversed if iBoolean is true. 这表示代码将始终更新iQuantity ,并且如果iBoolean为true,则更新将被反转。

Edit: Updated not to modify iDelta . 编辑:更新不修改iDelta

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM