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
putcharexpects a character code as its input. The character codes for digits from0to9may vary in different encodings, but theyalmostalways come sequentially (including in ASCII). This means that if you have the digitnand 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 thechartype, and treated like regular numbers, so addition is perfectly valid for them. However, it's important to realize that, inmostall 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'than48)Note that it, obviously, only works for singe digits, though.
EDIT: Fixed according to the comments