Thread: Question about subtracting char number

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    3

    Question about subtracting char number

    Hello,

    I spotted one piece of code where you as usual must indicate indice of an array to retrieve data. However, I saw some strange syntax.

    The array was like 10-15 elements long and contained strings.

    The statement was like this:

    cout << number[2 - '0' - 1] << endl;

    I don't understand what - '0' does.

    Could anyone explain this?

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    '0' is a character with with non-zero integral value that depends on character set. Subtracting '0' is often used to convert a character that is a digit to the corresponding value (i.e. '1' - '0' is 1, '2' - '0' is 2, etc).

    The actual value of of 1 - '0' (which is equivalent to 2 - '0' - 1) is implementation-defined. In practice, it depends on character set (ASCII, EBCDIC) your system supports.

    If you have quoted the statement correctly (not left out quote characters, or something) then the author of the code is doing some hack that assumes the compiler supports a specific character set.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char* value to Hex number
    By Notneo in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2011, 10:11 PM
  2. Replies: 6
    Last Post: 07-15-2008, 02:27 PM
  3. Replies: 5
    Last Post: 05-30-2003, 12:46 AM
  4. char number to same int number
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 07-18-2002, 05:22 PM
  5. Adding and subtracting.
    By erikcn in forum C++ Programming
    Replies: 2
    Last Post: 06-01-2002, 05:01 AM