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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With