Please have a look at this code:
#include <stdio.h>
int main(void)
{
short s;
int i = 65696;
float f = 65696.0F;
printf("sizeof(short) = %lu\n", sizeof(short));
s = i;
printf("s = %hd\n", s);
s = f;
printf("s = %hd\n", s);
s = 65696;
printf("s = %hd\n", s);
s = 65696.0F;
printf("s = %hd\n", s);
return 0;
}
It gave output as :
sizeof(short) = 2
s = 160
s = 160
s = 160
s = 32767
In last line why it’s 32767 and not 160 ? What’s the difference between saying f = 65696.0F; s = f; and s = 65696.0F; ?
Because if the integral part of the float value is not representable in the new type, the conversion is undefined behavior.
In your case,
SHRT_MAXis probably 32767 and so the integral part of65696.0Fis then not representable in ashortobject.