int a;
scanf("%c",&a);
printf("%d",a);

i/p:12,13,14,15,16
o/p:1963761201

i/p:65
o/p:1963761206

Please explain to the reason for this output?

That's what you get when you lie to scanf(). Assuming 4 byte integers, a looks like this (the question marks mean an indeterminate value):

[?][?][?][?]

Now when you pass the address of a into scanf() and say that it's a pointer to char, scanf() will do exactly what you asked and only fill in the first byte:

[d][?][?][?]

Now when you pass a into printf() and try to get the integer value, you get garbage because the remaining 3 bytes are still uninitialized. It's really no different in terms of undefined behavior than if you just did this:

int a;
printf("%d", a);

Edited 4 Years Ago by deceptikon

Thank you for replying sir.
Assuming integer is 2 bytes.
Bit representation of 12 is 00000000 00000000 00000000 00001100.
So,if one byte is filled and the rest neglected due to overflow shouldn't the output be garbage value in 1 byte and 12 stored in the other byte?

A noticeable trend in the output is
12-->1963761201(the last digit is 1)
22-->1963761202(the last digit is 2)
65-->1963761206(the last digit is 6)
What could be the reason for this?

Bit representation of 12 is 00000000 00000000 00000000 00001100.

12 has nothing to do with this. You may have typed 12, but scanf() read the numeric value of '1' and stored it in the first byte. Note also that depending on your system's endianness, the "first" byte may be either the most significant or least significant since scanf() is working directly with memory addresses and not endian-corrected values.

That is my last doubt,what is it that is happening inside?Why is the system reading only one when 12 can be easily represented in a single byte.

Why is the system reading only one when 12 can be easily represented in a single byte.

Because you asked scanf() for a char, not an int. It interprets the character representation of the key that you pressed, in this case '1'. The thing is that all input is in the form of a string. scanf() will do a string to xyz conversion where xyz is whatever type you requested, and it won't try to convert any more than that.

If you request a string or character, no conversion takes place. 12 becomes "12\0" as a string or '1' as a character (because '1' and '2' are separate characters). If you request an int, then "12" will be converted into 12.

This article has been dead for over six months. Start a new discussion instead.