开发者

Statements in C++

开发者 https://www.devze.com 2023-02-11 09:32 出处:网络
In C++ want to write something like this int Answer; if (Answer == 1 || Answer == 8 || 开发者_如何学JAVAAnswer == 10)

In C++ want to write something like this

int Answer;
if (Answer == 1 || Answer == 8 || 开发者_如何学JAVAAnswer == 10) 

and so on, is it any way to make code shorter without repeating variable always?


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.
 }


For readability I'd encapsulate the logic in descriptively-named functions. If, say, your answers are things with a particular color, and answers 1, 8, and 10 are green things, then you can write that logic as

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

Then your function becomes

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

If you have a lot of choices like this, I can see it getting hard to read if you have a lot of raw numbers all over the place.


If and only if you need to optimise for code size manually, and Answer is guaranteed to be positive and less than the number of bits in an int, you might use something like

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

But normally you don't want to obscure your logic like that.


You could put the values into a container and search the container.
Sounds like a std::set would be a wise choice:
if answer is in the set of (1, 8, 10) then do....

Remember that a std::set must be initialized during run-time, unlike numeric constants or an array of numeric constants. Before making any performance changes, first get the program working correctly, then profile if necessary, that is only if the program demands performance optimization.

0

精彩评论

暂无评论...
验证码 换一张
取 消