0
#include <stdio.h>
#include <stdlib.h>

//A simple program that asks for an integer and prints it back out.

int main()
{
    int a; 
    printf("Type an integer: ");
    scanf("%d",&a);
    printf("The integer you typed is: %d",a);
}

If the user types in a character such as X then the output will always be a 64 for some reason. Why does this happen?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
InKnight
  • 23
  • 2
  • 5
  • @CherubimAnand: It's not an ASCII thing. X isn't even ASCII 64. โ€“ user2357112 Jun 10 '16 at 19:07
  • @user2357112 Ya... its undefined behavior.. i got it wrong โ€“ Cherubim Jun 10 '16 at 19:08
  • In addition to what Sourav said, it's always a good idea to validate inputs (or arguments when in a function). If what is received is not what you intended, give a warning or error message. This is especially beneficial for helping debug a more robust problem. โ€“ Allen Jun 10 '16 at 22:31

1 Answers1

9

This invokes undefined behavior.

In case a matching failure happens for scanf() ("X" is not a match for %d), the supplied argument remains unassigned, and as the argument is an uninitialized local variable, the value remains indeterminate.

Related, from C11, chapter ยง7.21.6.2

[...] If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. [...]

Attempting to use that value invokes UB. From C11 annex J.2, undefined behavior

The value of an object with automatic storage duration is used while it is indeterminate.

Thus, you should always

  1. Initialize your local variables
  2. Check the return value of scanf().
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261