How does '0' + (n % 10) convert an integer digit to its character representation in C?

How does '0' + (n % 10) convert an integer digit to its character representation in C?
typescript
Ethan Jackson

I'm learning about converting numbers to characters in C, and I came across the expression:

char c = '0' + (n % 10);

I understand that '0' is a character and n % 10 extracts the last digit of a number, but I want to understand in detail:

Why do we add '0' to (n % 10)?

How does this relate to the ASCII table?

Why is '0' represented as 48 in ASCII, and how does adding a digit to it produce the correct character?

How can this be used to print numbers as characters?

Could someone please explain this concept step-by-step with examples? Also, how does the modulo % operator help in extracting digits from a number?

I tried printing the character values of digits by adding '0' to them, like this:

int digit = 5; char c = '0' + digit; printf("%c\n", c); // Expected output: '5'

I expected this to print the character '5', and it worked. However, I want to understand the underlying reason why adding '0' converts a digit to its character form, and how this ties into ASCII values and modulo operations.

Answer

  1. C standard in 5.2.1 3 guaranteed that character representation of decimal digits is contiguous:

    In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

  2. char type is an integer and it holds a number.

  3. '0' , '1' etc are character constants and have int type and value of the representation of the mapped character interpreted as an integer

  4. So if the integer representation of '0' is 48 then representation of '1' will be 49. It does not matter what encoding system computer uses (ASCII or something else).

  5. So '0' + <0,9> will provide integer representation of a digit.

Related Articles