Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten multiple && condition

Currently I can run my program but my code consists of a lot of repetition which looks something like:

while(option != 'E' && option != 'D' && option != 'P' && option != 'Q' &&
      option != 'e' && option != 'd' && option != 'p' && option != 'q') {
  // Some code here
}

or:

while(cType != 'S' && cType != 'L' && cType != 'O' && cType != 'Q' &&
      cType != 's' && cType != 'l' && cType != 'o' && cType != 'q') {
  // Some code here
}

What's the fastest way to shorten above code?

(Is there any way beside using additional function?)

like image 247
Vui La Chinh Avatar asked Aug 24 '15 18:08

Vui La Chinh


4 Answers

const char invalidChars[] = "edpq";
while (strchr(invalidChars, tolower(option)) != 0) {
    ...
}
like image 133
asdf Avatar answered Nov 04 '22 17:11

asdf


You could initialize a string containing the characters you want to match, then use find, which returns npos if no match was found:

string match = "SLOQsloq";
while (match.find(cType) == string::npos)
  ...
like image 3
Jon Purdy Avatar answered Nov 04 '22 16:11

Jon Purdy


You could get rid of half of the conditions with std::tolower

while(std::tolower(option) != 'e' && std::tolower(option) != 'd' && std::tolower(option) != 'p' && std::tolower(option) != 'q')

You could also use a std::string and it's find member function like:

std::string options = "edpq";
//...
while (options.find(std::tolower(option)) == std::string::npos)
like image 3
NathanOliver Avatar answered Nov 04 '22 18:11

NathanOliver


You could simplify the logic and make things more readable by using an std::set and checking if the set contains (or doesn't contain) the variable we're comparing to:

std::set<char> someChars { 'a', 'b', 'c' };
if(someChars.find(myChar) != someChars.end()) {
    // myChar is either 'a', 'b', or 'c'
}

The condition in most other languages would be written more cleanly as something like someChars.contains(myChar) (but C++'s set interface is very minimal).

However, for a small number of comparisons, your method is probably faster.

like image 2
Kat Avatar answered Nov 04 '22 16:11

Kat