468,512 Members | 971 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

How to compare chars ASCII codes in C???

44
Hi everybody! The following comparison of two chars does not work in a C program:

if( 'a' < 'z' ){

//do something...
}

This comparison works, for example, in Java, and my question is: how to do the same or in a similar way in C?

Gratefully yours
Aug 3 '06 #1
2 26240
Banfa
9,056 Expert Mod 8TB
Yes it does, that precisely works in a C program. However was is true for C and I suspect Java is that the C standard does not specify the character set (e.g. ASCII) it specifically states that the characters '0', '1', '2' ... '9' should have consecutive values but does not specify the same for the letters.

What this means is that ('a' < 'z') is actually dependent on the character set you are using, it is TRUE in ASCII and to be quite honest many C/C++ programmers rely on this fact which makes there code slightly non-portable however many many platforms use ASCII so I think we can probably forgive them this.

Here is a working program

Expand|Select|Wrap|Line Numbers
  1. #include "stdlib.h"
  2. #include "stdio.h"
  3.  
  4. int main(int argc, char* argv[])
  5. {
  6.     if( 'a' < 'z' ){
  7.  
  8.         printf( "a is less than z\n" );
  9.     }
  10.  
  11.     return EXIT_SUCCESS;
  12. }
  13.  
Aug 4 '06 #2
zeny
44

Here is a working program

Expand|Select|Wrap|Line Numbers
  1. #include "stdlib.h"
  2. #include "stdio.h"
  3.  
  4. int main(int argc, char* argv[])
  5. {
  6.     if( 'a' < 'z' ){
  7.  
  8.         printf( "a is less than z\n" );
  9.     }
  10.  
  11.     return EXIT_SUCCESS;
  12. }
  13.  

Thanks a lot, indeed the above code works. I tried to do exactly the same but the compiler reported errors. Im using Dev C++ 4 IDE and the compiler totally sucks, and most of the times i have to guess where are the errors because the errors reported by the compiler dont make any sense and are unspecific. So when the program gave errors i assumed that the comparison was invalid because i wasnt seeing any syntactic errors.
Aug 4 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

14 posts views Thread by Nicolas Bouillon | last post: by
28 posts views Thread by JKop | last post: by
4 posts views Thread by Siemel Naran | last post: by
43 posts views Thread by Bill Cunningham | last post: by
9 posts views Thread by simchajoy2000 | last post: by
6 posts views Thread by bruce | last post: by
14 posts views Thread by abhi147 | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.