Home >Backend Development >C++ >Why Does Subtracting '0' from a Char in C Return Its Numerical Value?
Subtracting '0' from a Char in C Returns Its Numerical Value
You may be surprised to discover that subtracting '0' from an ASCII character code results in the numerical value represented by that character.
Understanding ASCII Encodings
To understand why this works, it's important to know about ASCII encodings. ASCII assigns each character a unique numerical value, ranging from 0 to 127. The numerical value corresponding to a character is known as its ASCII code.
For example, the character '0' has an ASCII code of 48, '1' has an ASCII code of 49, and so on. This means that the characters '0' to '9' have ASCII codes in the range 48 to 57.
Numerical Representation of Characters
The reason subtracting '0' from a character code returns the numerical value is because the ASCII codes for the digits '0' to '9' are sequential. Subtracting '0' from any of these codes removes the digits' offset from the sequence, leaving only the actual numerical value.
For instance, subtracting '0' from '9' (ASCII code 57) yields 9, since 57 - 48 = 9.
Example
Consider the following code:
char c = '9'; int x = (int)(c - '0');
Here, we have a character '9' stored in the variable c. Casting the difference between c and '0' to an integer using (int) assigns the numerical value of '9', which is 9, to the variable x.
Conclusion
In conclusion, subtracting '0' from the ASCII code of a character in C results in the numerical value that the character represents because the ASCII codes for the digits '0' to '9' are sequential and represent the numerical values directly.
The above is the detailed content of Why Does Subtracting '0' from a Char in C Return Its Numerical Value?. For more information, please follow other related articles on the PHP Chinese website!