Why is '0' put in this the putchar function when I want a number printed

95 views Asked by At

I am trying to print numbers using the putchar() function. Here's my code below:

int main(void)
{

    int x = 0;

    for (; x <= 9; x++)
    {
      putchar(x + '0');
    }
    }
    _putchar('\n');
}

If run without the " + '0'", no result is visible on the shell.

Does this have to do with the ASCII? Who can help explain what's going on behind the scene?

Thanks

1

There are 1 answers

3
abel1502 On

putchar expects a character code as its input. The character codes for digits from 0 to 9 may vary in different encodings, but they almost always come sequentially (including in ASCII). This means that if you have the digit n and want to get the corresponding character, the simplest way to acheive that is to add the character code of '0' to it. (Character codes in C are represented by the char type, and treated like regular numbers, so addition is perfectly valid for them. However, it's important to realize that, in most all C-compatible encodings, '0''s character code is not 0. In ASCII in particular, it's 48. But it's more comprehensible and universal to write '0' than 48)

Note that it, obviously, only works for singe digits, though.

EDIT: Fixed according to the comments