基于数值(正、负、零)实现条件表达式的最佳方法

Kyl*_*ker 2 c++ optimization if-statement

是否有更好更优雅的方式来实现以下幼稚的代码(diffYear、A 和 B 是数字):

diffYear = yearA - yearB;

if (diffYear == 0) {
    A = B = 0;  
}
else if (diffYear > 0) {
    A = diffYear * -1;
    B = 0;
}
else if (diffYear < 0) {   // obviously one could only write a simple else, this is for the sake of the example
    A = 0;
    B = diffYear;
}
Run Code Online (Sandbox Code Playgroud)

YSC*_*YSC 6

这个实现很好。

有没有更好的优雅方式来实现下面的代码

经验法则是:它在做什么很清楚吗?如果是,请留下。


其他实现也是可能的,但您必须考虑谁将阅读此代码。例如,在一个团队/组织中,大多数开发人员每天都使用数学,我会写如下内容以使他们看起来更“自然”:

auto neg(int x) { return x < 0 ? x : 0; }
//...
int const A = neg(yearB - yearA);
int const B = neg(yearA - yearB);
Run Code Online (Sandbox Code Playgroud)