Search code examples
cterminaloutputeofkernighan-and-ritchie

Why single digit numbers are appended with "D" (in C output)?


Why single digit numbers are appended with "D" (in C output)?

The following code

#include <stdio.h>

int main(void)
{
    int c = 0;

    printf("%d\n", c); 

    return 0;
}

once compiled & ran, outputs 0, as I would expect it to.
Though, this code

#include <stdio.h>

int main(void)
{
    int c = 0;

    while (getchar() != EOF) {
        ++c;
    }

    printf("%d\n", c); 

    return 0;
}

once compiled & ran, after triggering EOF right away -- outputs 0D for some reason, though value of c (as far as I can see) should be absolutely the same as in the first case.
Same happens for all the single digit numbers (i.e. 1D, 2D, 3D ... 9D), starting with 10 the appending D is not seen anymore.

I'd like to know:

  1. Why D is appended to the output in the second case, but not in the first (even though c should hold the same value)?

  2. Is it possible to avoid this D appending (and how, if it is)?


Solution

  • Your code simply cannot output a "D" for whatever reason. Not unless something really iffy happens, like a bug in the compiler or glibc. Or maybe a bitflip in memory.

    The "D" is very likely due to the terminal you're using, but your code simply CANNOT output it.

    Well, there is a very small chance. If you read more than INT_MAX characters, then the signed integer c will overflow, thus invoking undefined behavior. It's not likely that this would output a "D", but it's possible.