confusion with comparison of char

Jun 4, 2013 at 3:38pm
Why is this output as true. Arn't 0 and 9 converted to their ascii equivalents and numbers are lower in ASCII so 9 is not lower?

1
2
3
 ch3 = 'C';

cout << "'0: " << ('0' < ch3 < '9') << endl;
Jun 4, 2013 at 3:51pm
You can't chain comparisons like that.

What you probably want is:

1
2
3
'0' < ch3 && ch3 < '9'
// or
'0' < ch3 and ch3 < '9' // although this may raise some eyebrows 


What I think happens in your original code is:
1) '0' < ch3 gets evaluated to true which is 1.
2) 1 < '9' gets evaluated to true
Jun 4, 2013 at 3:56pm
Relational operators are evaluated from left to right. '0' < foo < '9' is about same as
1
2
bool tmp = '0' < foo;
tmp < '9'
Jun 5, 2013 at 12:23am
cool cool makes perfect sense. Thankyou.
Topic archived. No new replies allowed.