Question

on page 23 in the K&R second edition, there is some code

    if (c >= '0' && c <= '9')
       ++ndigit[c-'0'];

It goes on. My question is, why do the integers have the ' on each side? and what is the c-'0'?

Was it helpful?

Solution 2

The purpose of the code is to convert the characters '0'...'9' into the corresponding integer values 0...9. C does not guarantee that the characters representing decimal digits have any particular value, but it does guarantee that they are consecutive and in the correct order. The subtraction above will always give you the correct integer value.

There is no similar guarantee for any other character in C.

References

The ISO 9899:1999 Standard (aka C99) says:

The values of the members of the execution character set are implementation-defined. ...

A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string. ...

the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Exactly the same wording is found in N1570, which was the final public draft of the current standard (C11).

Not much else is said about the values of, or relationship between characters.

OTHER TIPS

'0' is a character. It has the integer value 48. '9' has the value 57. The value of c - '0' is equal to c - 48, and will be the integer value of the corresponding character. '0' will be 0, '1' will be 1, etc.

'0' is a char, i.e. a character. Every character is internally represented by an integer. See ASCII. For example, '0' has the integer value 48.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top