PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

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

 August 17, 2022     c, eof, kernighan-and-ritchie, output, terminal     No comments   

Issue

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.



Answered By - klutt
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing