/* Function converts ch to an integer if it is a digit. Otherwise, it
prints an error message.
*/
int dig_to_int(char ch)
{
if (IS_DIGIT(ch))
return ch - '0';
printf("ERROR:dig_to_int: %c is not a digit\n", ch);
return ERROR;
}
so when we say:
ch - '0'
the code evaluates
'4' - '0'
which the hardware sees as
52 - 48
which is
4
We can use the same technique to convert an integer, in the range 0-9, to a character:
/* Function converts a positive integer less than 10 to a corresponding
digit character.
*/
char int_to_dig(int n)
{
if (n >= 0 && n < 10)
return n + '0';
printf("ERROR:int_to_dig: %d is not in the range 0 to 9\n", n);
return NULL;
}
when we say:
n + '0'
the code evaluates
4 + '0'
which the hardware sees as
4 + 48
which is
52
which, as a character is:
'4'
to Overview.