Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

terminal - 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
", 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
", 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)?

question from:https://stackoverflow.com/questions/65915451/why-single-digit-numbers-are-appended-with-d-in-c-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...