Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statements in C++

In C++ want to write something like this

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

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

like image 500
Templar Avatar asked Nov 30 '22 17:11

Templar


2 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.
 }
like image 129
xanatos Avatar answered Dec 16 '22 00:12

xanatos


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.

like image 29
John Avatar answered Dec 15 '22 22:12

John