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.
There is nothing wrong about nesting conditionals in a
returnstatement, per se.~result + 1is bad. You are attempting to negateresult. The proper way to do this is simply-result.~result + 1relies on two’s complement representation, which is ubiquitous, but this expression is weirder and unnecessary.You do not need
(result < 0 ? ~result + 1 : result). This expression is evaluated only ifx > baseis false, in which caseresultmust 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 (return0, which is the same as-resultwhenresultis zero).So the
returnstatement can be written:or: