2

So I was wondering what happens if the user enters characters in integer variables for example:

main()
{

    int number;

    printf("Print a number:");
    scanf(" %d", &number);
    printf("The result is:%d", number);

    return 0;
}

I typed in characters and the result is: 1986895412

is this 1986895412 a place in the ram ??

J...S
  • 5,079
  • 1
  • 20
  • 35
user3103230
  • 63
  • 1
  • 6

3 Answers3

8

In this case, scanf directive just fails. Quoting this answer (which essentially rephrases the spec's definition):

The %d conversion specifier expects the input text to be formatted as a decimal integer. If it isn't, the conversion fails and the character that caused the conversion to fail is left in the input stream.

So, number remains with the same value it had before the directive. As you didn't initialize it with some defined value (like int number = 0), it'll be just some random garbage value. In your case that happened to be equal to 1986895412.

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229
1

Check the return of scanf(). When you type in characters, the correspond result will occur.

if (1 == scanf("%d", &number)) {
  printf("The result is:%d", number);
}
else {
  printf("Invalid data entered.  `number` not changed\n");
}

Note: Code's int number; is not initialized, so its value could be any int. With invalid input, number was not changed and code printed the uninitialized number which just happeded to have the value of "1986895412". It may differ tomorrow.

Note: leading space in " %d" is not needed as %d itself consume leading whitespace.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

As number had not been initialized and scanf() failed the printf() provokes undefined behaviour reading the uninitialised variable number. Anything could happen.

So there are two lessons to learn here:

  1. Initialise variables when they are defined. (If you do not know to what to initialise them you most probably do not need them, at least not where you are trying to define them)
  2. Perform error checking on calls which would return garbage if failed.
alk
  • 69,737
  • 10
  • 105
  • 255