Quote:
/* K&R pp.43 */
As we discussed in Chapter 1, the expression
s[i] - '0'
gives the numeric equivalent of the character stored in s[i], because the values of '0', '1', etc., form a contiguous sequence.
Another example of char to int conversion is the function lower, which maps a single character to lower case for the ASCII character set.
<snip code>
This works for ASCII because the corresponding upper and lower case letters are a fixed distance apart as numeric values and each alphabet is contiguous -- there is nothing but letters between A and Z. This latter observation is not true of the EBCDIC character set, however, so this code would convert more than just letters in EBCDIC.
Quote:
/* K&R pp.22-23 */
This particular program relies on the properties of the character representation of the digits. For example, the test
if (c >= '0' && c <= '9') ...
determines whether the character in c is a digit. If it is, the numeric value of that digit is
c - '0'
This works only if '0', '1', ..., '9' have consecutive increasing values. Fortunately, this is true for all character sets.
So your statement that the code will only work on ASCII is not explicitly stated by K&R for a number conversion from char to int, in fact it could be interpreted that they even state that it will work on all character sets. I've personally never tried it on a machine that uses EBCDIC, but I have no reason to believe that it will not work since EBCDIC defines 0 through 9 as