c - What type-conversions are happening? -


#include "stdio.h"  int main() {     int x = -13701;     unsigned int y = 3;     signed short z = x / y;      printf("z = %d\n", z);      return 0; } 

i expect answer -4567. getting "z = 17278". why promotion of these numbers result in 17278?

i executed in code pad.

the hidden type conversions are:

signed short z = (signed short) (((unsigned int) x) / y); 

when mix signed , unsigned types unsigned ones win. x converted unsigned int, divided 3, , result down-converted (signed) short. 32-bit integers:

(unsigned) -13701         == (unsigned) 0xffffca7b // bit pattern (unsigned) 0xffffca7b     == (unsigned) 4294953595 // re-interpret unsigned (unsigned) 4294953595 / 3 == (unsigned) 1431651198 // divide 3 (unsigned) 1431651198     == (unsigned) 0x5555437e // bit pattern of result (short) 0x5555437e        == (short) 0x437e        // strip high 16 bits (short) 0x437e            == (short) 17278         // re-interpret short 

by way, signed keyword unnecessary. signed short longer way of saying short. type needs explicit signed char. char can signed or unsigned depending on platform; other types signed default.


Comments

Popular posts from this blog

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -

openssl - Load PKCS#8 binary key into Ruby -