nsit_poison
nsit_poison

Reputation: 129

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;
}

Upvotes: 2

Views: 940

Answers (3)

Zaphod Beeblebrox
Zaphod Beeblebrox

Reputation: 679

Because the stack gets corrupted. Suppose the "short int" type takes 2 bytes on your platform, while the "int" type takes 4 bytes. Variables a, b, c, d, e, f are allocated on the stack and they are assigned 2 bytes each. Each time you read a value using the "%d" specifier, instead of "%hd", you tell scanf() to memorize it as an "int", taking 4 bytes instead of 2. That produces, of course, unpredictable results. In my experience, the usage of scanf() gives more headaches than benefits :-) so you might want to use the safer fread() and then convert the string into an integer.

Upvotes: 0

Alam
Alam

Reputation: 1596

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

Upvotes: 3

CB Bailey
CB Bailey

Reputation: 792059

The correct scanf format specifier for short int is %hd, not plain %d. You are experiencing the results of undefined behavior.

Upvotes: 8

Related Questions