Expressions in C ++

In C ++ I want to write something like this

int Answer; if (Answer == 1 || Answer == 8 || Answer == 10) 

etc., is it possible to make the code shorter at all without a repeating variable?

+4
source share
4 answers

Try:

  switch (Answer) { case 1: // fall through case 8: // fall through case 10: // ... do something break; // Only need if there are other case statements. // Leaving to help in mainenance. } 
+14
source

For readability, I encapsulated the logic in descriptively-named functions. If, say, your answers are things of a certain color, and the answers 1, 8 and 10 are green things, then you can write this logic as

 bool ChoiceIsGreen(int answer) { return (answer == 1 || answer == 8 || answer == 10); } 

Then your function will become

 if (ChoiceIsGreen(Answer)) { // offer some soylent green } 

If you have many options like this, I can see that it becomes difficult to read if you have a lot of raw numbers everywhere.

+6
source

If and only if you need to optimize the code size manually, and the answer is guaranteed to be positive and less than the number of bits in int, you can use something like

 if ( ( 1 << Answer ) & 0x502 ) 

But usually you don’t want to hide your logic.

+1
source

You can put values ​​in a container and search in the container.
It looks like std::set would be a wise choice:
if the answer is in set (1, 8, 10), then do ....

Remember that a std::set must be initialized at run time, unlike numeric constants or an array of numeric constants. Before making any changes in performance, first make sure that the program is working correctly, and then profile if necessary , only if the program requires performance optimization.

0
source

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


All Articles