Thread: Quick Question

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    126

    Quick Question

    In this function to get it to add the value at *i correctly I have to negate char 0. This will probably seem dumb but why do I have to do this for it to work properly?

    Code:
    int sum_digit(char array[200], int *digCount, int *i)
    {
    if (array[(*i)] >= '0' && array[(*i)] <= '9'){
    
            (*digCount)+= (int)array[*i]-'0';
        
    return *digCount;}
    }

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    You don't "negate char 0". You subtract the value '0' (which is 48 in ASCII computers) from whatever is in the array.

    All characters, in C, have a numeric value (like 48 or 97 or 10 ...).
    The Standard mandates that the digits have sequential numbers. This means that the character '1' has a value that is 1 higher than the value of '0', the character '2' is 2 higher than the value of '0', ...
    By taking any character whatsoever, your if condition limits it to one of '0', '1', ..., '9'.
    If you take the value of '0' from '0' (even if your computer is not an ASCII based computer) you get the value 0; if you take the value '0' from '1' you get 1, ..., ...

    To sum up: subtracting '0' (value of a character) from a digit yields the numeric value of the digit ('8' - '0' yields 8).

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    126
    Yes but '8' = 8 which is why I guess my understanding is lacking, I understand that C has ascii values for chars and numbers.

  4. #4
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Quote Originally Posted by Sorinx View Post
    Yes but '8' = 8...
    No. '8' has a value that depends on the character set used by the implementation. On ASCII based implementations that value is 56; on EBCDIC based implementations that value is 248.
    '8' - '0', in all implementations is the value 8.

  5. #5
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A quick question...
    By MarioI in forum C Programming
    Replies: 9
    Last Post: 02-10-2011, 07:36 PM
  2. A quick question
    By abh!shek in forum C++ Programming
    Replies: 22
    Last Post: 04-20-2008, 11:14 AM
  3. Quick Question
    By SinAmerica in forum C++ Programming
    Replies: 2
    Last Post: 10-23-2002, 02:28 AM
  4. quick question (please help
    By CBeginner in forum C++ Programming
    Replies: 11
    Last Post: 10-22-2002, 01:31 PM
  5. quick question
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 12-19-2001, 01:34 PM