vinay hunachyal
vinay hunachyal

Reputation: 3891

How does unsigned short int differs from unsigned int

#include<stdio.h>
 int main()
 {
    unsigned  short int  x=-10;
    short int y=-10;
    unsigned int z=-10000000;
    int m=-10000000;

    printf("x=%d y=%d z=%d m=%d",x,y,z,m);
    return 0;
 }

output=x=65526 y=-10 z=-10000000 m=-10000000

My query is How unsigned short intdiffer from unsigned int in the scenario of data holding. i.e x=65526 where as z=-10000000 why x is not equal -10 where as z can hold any data As short is 2 byte so twos complement -10 is 65526 but why not same in case of z

Upvotes: 1

Views: 1045

Answers (1)

chux
chux

Reputation: 153358

When unsigned short int x=-10; occurs, x, being unsigned, gets a modulo or "wrapped" value of 65526 (OP sizeof(short) is 2). Something like x = power(256,sizeof(unsigned short)) - 10.

When x is printed, it is passed to printf() as an int (variadic promotion). OP's sizeof(int) is 4, so the 65526 fits in int. Then printf() sees a %d and prints "65526".

z Has a similar story, but sizeof(z) is 4. and gets initialized z = power(256,sizeof(unsigned)) - 10.

Your printf() is using the %d specifier for unsigned. OP should use %u.

printf("x=%u y=%d z=%u m=%d",x,y,z,m);

unsigned short int is guaranteed to cover at least the range 0 to 65535.

unsigned int is guaranteed to cover at least the range of unsigned short int. It may cover a wider range.

unsigned int is usually the native size the processor best uses - typically fastest.

As unsigned short int is, in some implementations, smaller than unsigned int. It is preferred for space saving with large arrays.

Upvotes: 4

Related Questions