Question about subtracting char number

This is a discussion on Question about subtracting char number within the C++ Programming forums, part of the General Programming Boards category; Hello, I spotted one piece of code where you as usual must indicate indice of an array to retrieve data. ...

  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,537
    '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 in reply to you, it is likely you deserve it. Suck it up, sunshine, 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, 11:11 PM
  2. Replies: 6
    Last Post: 07-15-2008, 03:27 PM
  3. Replies: 5
    Last Post: 05-30-2003, 01:46 AM
  4. char number to same int number
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 07-18-2002, 06:22 PM
  5. Adding and subtracting.
    By erikcn in forum C++ Programming
    Replies: 2
    Last Post: 06-01-2002, 06:01 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21