Nesting conditional operators in a return statement

97 views Asked by At

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. 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? Is there an emoji for beating a dead horse? Because i'd like to use it.

1

There are 1 answers

0
Eric Postpischil On BEST ANSWER
  1. There is nothing wrong about nesting conditionals in a return statement, per se.

  2. ~result + 1 is bad. You are attempting to negate result. The proper way to do this is simply -result. ~result + 1 relies on two’s complement representation, which is ubiquitous, but this expression is weirder and unnecessary.

  3. You do not need (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).

So the return statement can be written:

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

or:

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