Search code examples
cscanf

Short int doesn't take the value


The input given to following program is

10 10

10 10

But the output is

0 20

Why ?

/* scanf example */
#include <stdio.h>


int main ()
{
    short int a, b, c, d, e, f;
    a=b=c=d=e=f=0;
    scanf("%d %d",&a,&b);
    scanf("%d %d",&e,&d);
    c=a+b;
    f=d+e;

    printf("%d %d\n",c,f);

    return 0;
}

Solution

  • You have taken 6 variables a, b, c, d, e, f. The memory allocated by them are 2 bytes and the starting memory address are say for f 0x0, e 0x2, d 0x4, c 0x6, b 0x8, a 0xa

    when you are doing scanf("%d %d",&a,&b) first value for a is written from memory location 0xa, occupying 4 bytes till 0xe. Then value for b is written starting from location 0x8 occupying 4 bytes till 0xc, thus overwriting memory location of a. same with other scanf. You will get different values if you change the order of memory location.

    Please note output is dependent on the platform you are using hence undefined behaviour