Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if C tries to scan character in integer variable [duplicate]

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 ??

like image 953
user3103230 Avatar asked Dec 19 '25 19:12

user3103230


1 Answers

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.

like image 95
raina77ow Avatar answered Dec 22 '25 11:12

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!