1

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

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
SJP
  • 31
  • 6
  • 1
    Your posted code does not compile. It is missing all `#include` directives and the `{` an `}` are mismatched. Also, what is `_putchar`? You seem to be calling a platform-specific function. Did you mean `putchar`? – Andreas Wenzel Jul 21 '23 at 17:04
  • Oh, apologies. "_putchar()" was a modified function that I had put in another header "main.h". That was included at the beginning of the code " #include "main.h" – SJP Jul 27 '23 at 19:26

1 Answers1

5

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

abel1502
  • 955
  • 4
  • 14
  • 2
    The character codes for digits 0 to 9 are guaranteed to be sequential in the C specification. (That is not true for the letters a-z, A-Z.) – Ian Abbott Jul 21 '23 at 16:56
  • 3
    Re: *"almost always come sequentially"* - the C standard requires that `'0`' .. `'9'` be sequential in both the source and execution character set. For example, [C11 §5.2.1](https://port70.net/~nsz/c/c11/n1570.html#5.2.1). – Oka Jul 21 '23 at 16:57
  • 4
    Also, `'0'` cannot be zero in any encoding; zero is reserved for the null terminator. – Eric Postpischil Jul 21 '23 at 16:58