-3

I'm working on a simple function to convert ascii codes to array indexes, and I'm have a bit of trouble with the else-if statement.

int getIndex(char character) {
    int code = int(character);
    int index = -1;

    if (code == int(' ')){
         index = 26;
    }  else if (int('a') <= code <= int('z')) {  
        index = code - int('a');
    }     
    return index;
}

The if condition works fine and fires on spaces, but the else if statement fires in every other case, regardless of whether the character is in the range a to z or not. Is there a problem I can't see with the condition?

Bonnie L
  • 3
  • 2
  • This isn't the problem, but you don't need to cast `' '` (or any of the other character literals) to `int`; the compiler will convert it to match the `int` on the other side of the `==`. – Pete Becker May 27 '17 at 12:36

1 Answers1

2

doesn't support expressions with multiple comparisons (like, e.g., does). You need to break the expression in the else if branch into two expression with the logical and (&&) operator between them:

if (code == int(' ')){
     index = 26;
}  else if (int('a') <= code && code <= int('z')) {  
    // Here -----------------^
    index = code - int('a');
}     
return index;
Mureinik
  • 297,002
  • 52
  • 306
  • 350