Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to write if-conditionals with repetitive variable

I'm looking for a more efficient way to write these kinds of if-conditionals:

a = huge_term >= b ? huge_term : c

or

(a = huge_term) >= b ? a : a = c

The second one is quite shorter but the variable a appears 3 times. I need the result to be stored in a variable. How would you write it?

like image 872
ericMTR Avatar asked Mar 24 '23 02:03

ericMTR


2 Answers

I recommend using intermediate variables and breaking up the logic into its own function. Generally, whenever I find conditional logic like this, it shows up again and again in my project, so refactoring it saves time in the long run.

Type processInput(const Type input)
{
  auto result = input;
  if ( input < b )
  {
    result = c;
  }
  return result;
}

int main()
{
  const auto input = huge_term;
  const auto result = processInput(input);
}
like image 118
Bill Avatar answered Apr 06 '23 11:04

Bill


Your first method is ok but additional complication of the expression will make it unreadable and it would probably be better to use if instead.

The second "method" is both unreadable and inefficient - redundant computations are present. Don't do that.

like image 32
SomeWittyUsername Avatar answered Apr 06 '23 11:04

SomeWittyUsername