简体   繁体   English

在 return 语句中嵌套条件运算符

[英]Nesting conditional operators in a return statement

So I setup a code that finds the magnitude (absolute value) of the difference between the user's input and 51. If the user's input is greater than 51 the result is tripled.因此,我设置了一个代码,用于查找用户输入与 51 之间差异的幅度(绝对值)。如果用户输入大于 51,则结果将增加三倍。 Not complicated.不复杂。 In an effort to minimize the code itself I came up with this.为了尽量减少代码本身,我想出了这个。

// Compare and determine the correct output based on program's 
// paramters:
//
// - find absolute value of input - 51
// - if input > 51 then multiply result by 3
//-----------------------------------------------------------

int calcDiff(int x) {
      const int base = 51;
      int result     = x - base;    
      return x > base ? 3*result : (result < 0 ? ~result + 1 : result);
 }

So the question is:所以问题是:

Is this appropriate?这合适吗? I know it works but i'm more curious whether it's bad practice and can some how bite me in the rear in a big way some day.我知道它有效,但我更好奇这是否是不好的做法,以及有一天会如何严重咬我。 Is this just opinion or is it a big no no like using scanf or gets ?这只是意见还是不喜欢使用scanfgets Is there an emoji for beating a dead horse?有打死马的表情包吗? Because i'd like to use it.因为我想用它。

  1. There is nothing wrong about nesting conditionals in a return statement, per se .return语句中嵌套条件本身并没有错。

  2. ~result + 1 is bad. ~result + 1不好。 You are attempting to negate result .您正在尝试否定result The proper way to do this is simply -result .正确的方法是简单的-result ~result + 1 relies on two's complement representation, which is ubiquitous, but this expression is weirder and unnecessary. ~result + 1依赖于无所不在的二进制补码表示,但这种表达更奇怪且没有必要。

  3. You do not need (result < 0 ? ~result + 1 : result) .你不需要(result < 0 ? ~result + 1 : result) This expression is evaluated only if x > base is false, in which case result must be less than or equal to zero, and you want to return -result , as that handles both the less than zero case (return -result ) and the equal to zero case (return 0 , which is the same as -result when result is zero).仅当x > base为假时才计算此表达式,在这种情况下result必须小于或等于零,并且您想要返回-result ,因为它处理小于零的情况(返回-result )和等于为零的情况(返回0 ,当result为零时与-result相同)。

So the return statement can be written:所以return语句可以写成:

return x > base ? 3*result : -result;

or:或者:

return result > 0 ? 3*result : -result;

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

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