More efficient way to write if conditionals with a repeating variable

I am looking for a more efficient way to write these types of if-conditional expressions:

a = huge_term >= b ? huge_term : c 

or

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

The second option is shorter, but the variable a appears 3 times. I need a result to store in a variable. How would you write it?

+4
source share
3 answers

I recommend using intermediate variables and breaking the logic into its own function. As a rule, whenever I find such conditional logic, it appears again and again in my project, so refactoring saves time in the end.

 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); } 
+7
source

Your first method is fine, but further complicating the expression will make it unreadable, and it would probably be better to use if instead.

The second "method" is unreadable and inefficient - there are redundant calculations. Do not do that.

+1
source

It is definitely better to have a variable appearing several times than a large expression.

This may not make a difference in efficiency in any case, but from the point of view of the organization of the program it is better not to repeat large blocks of code.

If huge_term is something that the compiler can recognize as a common subexpression whose value does not change between the two evaluations, it can be eliminated using CSE (general subexpression exception). But just because the compiler can reduce this does not mean that this is not a maintenance headache.

How many times a variable appears, hardly anything needs to be disturbed, especially if it helps reduce the repetition of a large expression. That is, if the variable is not a volatile memory cell, such as an I / O port. If assigning a is an externally visible effect, then the two versions do not have the same semantics.

-1
source

Source: https://habr.com/ru/post/1479038/


All Articles