Home > database >  Character type gives a int — what is this int?
Character type gives a int — what is this int?

Time:12-29

In a C program, I want to take an int type input but after I run the program, I will give a character type as input but it doesn't get any error and it shows an integer. Why?

Code:

#include <stdio.h>

int main(){

    int x;

    printf("input: ");

    scanf("%d", &x);

    printf("the output is %d",x);

    return 0;

}

After compilation:

input: a
the output is -1225407932
[Program finished]

CodePudding user response:

You do get an error but you ignored it.

When you type a but scanf() is told to expect an integer, it returns 0 indicating that it failed to convert any input into a number (but that there was data to process; it did not encounter EOF). The character you typed is still in the input buffer, waiting to be processed by a subsequent I/O operation.

The variable x that you passed to scanf() is still uninitialized after the call — it was not modified by scanf() because the conversion failed. Technically, printing an uninitialized variable such as x invokes undefined behaviour, but in practice, you get some quasi-random value output.

CodePudding user response:

If you have initialized the variable you would have got the output as 0. It doesn't give an error because char is just a 8-bit integer which can fit int on into.

  •  Tags:  
  • c
  • Related