Jack
Jack

Reputation: 16724

Choose of a lot of cases instead of c >= '0' && c <= '9' to 0-9 numbers checking

The following code is part of an intepreter that I'm reading. I'm trying to figure why exactly use this instead of simple c >= '0' && c <= '9'?

switch(ch) {
  //...
  case '0': case '1': case '2': 
  case '3': case '4': case '5':
  case '6': case '7': case '8':
  case '9': 
  //etc
  break;
  //more cases
}

I'm very curios too why choose use a switch for that. How it is a code of a interpreter,I believe that the author have a background C know. Is this fastest than c >= '0' && c <= '9' condition or is this some way to leave the compiler make some optmization? it's compiled by using gcc

Upvotes: 0

Views: 2822

Answers (5)

ArtFeel
ArtFeel

Reputation: 11801

If you use GCC or Clang you can also write:

switch(ch) {
  //...
  case '0' ... '9': 
  //stuff
  break;
  //more cases
}

Upvotes: 0

Mike Woolf
Mike Woolf

Reputation: 1210

As @Zack mentioned, it depends a great deal on what the "more cases" are. Many compilers will generate an optimized combination of conditional instructions and jump tables when there are a lot of cases in the switch. It's not necessarily just a matter of readability.

Upvotes: 1

Yang
Yang

Reputation: 8170

You can not use a condition in a switch case. If you want to use c >= '0' && c <= '9', then you have to use an if statement, then it possibly makes checking other cases difficult, for example:

if (c >= '0' && c <= '9') {
  // ...
} else if (c == 'a') {
  // ...
} else if (c == 'b') {
  // ...
} else if (c == 'c') {
  // ...
} // more cases

will probably not be better than

switch(ch) {
  //...
  case '0': case '1': case '2': 
  case '3': case '4': case '5':
  case '6': case '7': case '8':
  case '9': 
  //etc
  break;
  case 'a': //...
  case 'b': //...
  case 'c': //...
  //etc
}

Upvotes: 3

BLUEPIXY
BLUEPIXY

Reputation: 40145

maybe

if(isdigit(ch)){
    //etc
} else {
    //more cases
}

Upvotes: 2

Jon
Jon

Reputation: 437664

Specifically for digits only, this is guaranteed to produce the same results as the equivalent if.

However, depending on the "more cases" part the code may be easier to read when written using switch. For example, if "more cases" wants to catch all lowercase letters it would be theoretically wrong to write the test like this:

if (c >= 'a' || c <= 'z')

so you would have to write it like this:

if (c == 'a' || c == 'b' || ...)

In this case, it's much easier to use switch than if/elseif.

Upvotes: 2

Related Questions