Search code examples
cprintfprogram-entry-pointstdio

My C program prints -39 on a new line and I can't figure out why


I've been playing around and trying to experiment with C for my university class and I've found something that my program does even though I did not tell it to!

My full code:

#include <stdio.h>

int main(void) {
  int c;
  while ((c = getchar()) != EOF) {
    printf("%d\n", (c - '1'));
  }
 return 0;
}

The output of it looks like this:

7
6
-39

Now, can anyone tell me why that -39 is being printed?


Solution

  • Pretty clear if you look at this. First you entered 8 then 7 and then you entered \n (or pressed ENTER) which has ASCII value of 10. 10-49 (49 being the ascii value of '1') is -39 you have printed it.