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 (ie 1D
, 2D
, 3D
... 9D
), starting with 10
the appending D
is not seen anymore.
I'd like to know:
Why D
is appended to the output in the second case, but not in the first (even though c
should hold the same value)?
Is it possible to avoid this D
appending (and how, if it is)?
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.
When posting the question, I thought this behaviour has something to do with cases like this , but, as it turned out, it has nothing to do with the code and is solely terminal behaviour .
Suggestion by Some programmer dude in a comment, is exactly right: terminal simply outputs ^D
and output of the program then overwrites ^
, but not D
, thus for single-digit numbers output ends up being appended with D
.
Two (or more) digit numbers simply overwrite the whole ^D
.
I was able to verify this by changing EOF
triggering sequence to Ctrl + L (by stty eof ^L
), then the output becomes 1L
, 2L
, 3L
... 9L
.
As Jonathan Leffler said in comment above disabling echoing of control characters (by stty -echoctl
) would solve the issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.