First, you have to remember that characters in C are represented as tiny integers corresponding to the character's value in the machine's character set, which is typically ASCII.
For example, 'A'
n ASCII is 65, and '0'
is 48.
So if you're converting a string of digits to an integer, you want to do something like
int digit = c - 48;
That converts '0'
to 0, '1'
to 1, etc.
But that magic number 48 is mystifying, and it's theoretically also wrong on a machine using a character set other than ASCII. So the easier (because you don't have to remember that value 48), self-documenting (as long as your reader understands the idiom), and more portable way is to do
int digit = c - '0';
This works because, as I said, '0'
is 48 in ASCII. But, more importantly, even on a non-ASCII machine, '0'
is whatever value the character '0'
has in that machine's character set, so it's always the right value to subtract, no matter what kind of machine you're using.