C Programming – Understanding c-‘0’

c++

I was trying to test one of the K&R function which uses c-'0'. To understand clearly I wrote a two line code as below. My question is why is it printing "1". And what does the "numeric value" actually mean in this context. Thanks!

char c = 'a';
printf("%c",c-'0');

Best Answer

c - '0' only has a definite specific value when c is a digit ('0', '1', ..., or '9').

When c is '0', '0' - '0' is 0 because they are equal when c is '1', '1' - '0' is 1 because '1' immediately follows '0' in any character set any C implementation choses to use. The same for '2' and the other digits: '9' - '0' has a value of 9.

And you really shouldn't print a value with the "%c" format specifier.

Related Question