Thread: c char

  1. #1
    Registered User
    Join Date
    Aug 2013
    Posts
    17

    c char

    can i do in this way to check if letter is upper case or lower case
    is it better to using casting or i can do without casting thanks very much
    Code:
    if(selectOption == (char)81){
                selectOption = (char)113;
            }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Well, yes, you can do it that way. However, what you can do is not always a good idea.

    Neither the casting nor the magic values (81 and 113) are required. By using them, you're making your code both harder to read and not portable.

    Assuming your character set is based on ASCII (and you're doing this to convert a 'Q' to a 'q') then the more readable (direct) equivalent of your code is
    Code:
    if (selectOption == 'Q')
    {
         selectOption = 'q';
    }
    The advantage of this is it would work with ANY character set that contains uppercase 'Q' and lowercase 'q', not just ASCII and related character sets (and, yes, there are real-world compilers that support other character sets).

    An even more general approach is
    Code:
         selectOption = tolower(selectOption);
    where tolower() is declared in the standard header file <ctype.h>. The difference, however, is that it converts all uppercase letters to lowercase (not just 'Q'), and it also works in non-english speaking locales (assuming system is set up appropriately). Optionally, since tolower() returns an int not a char, this can be assisted with a type conversion
    Code:
         selectOption = (char)tolower(selectOption);
    which will stop some compilers warning (since truncating from int to char loses information). However, even without the type conversion the code is technically correct.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Aug 2013
    Posts
    17
    thanks very much everything is clear

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  2. Replies: 4
    Last Post: 07-24-2012, 10:41 AM
  3. undefined reference to `RunSwmmDll(char*, char*, char*)'
    By amkabaasha in forum C++ Programming
    Replies: 1
    Last Post: 10-31-2011, 12:33 PM
  4. Read File To Char Array with Null char init
    By MicroFiend in forum Windows Programming
    Replies: 1
    Last Post: 10-28-2003, 06:18 PM
  5. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM