Search code examples
cbit-manipulation

If we have a long variable which we return from a function, and store the returned value in int variable, which bits will be stored?


Suppose there is the following code :

unsigned int foo()
{
   unsigned int var = 0x12345678;// assuming 4 bytes
   return var;
}

void bar()
{
    unsigned short res = foo(); //assuming short is 2 bytes
} 

What can be the expected value of res?


Solution

  • The last 16 bits should be used as the value of the unsigned short (res).

    0x12345678 is 10010001101000101011001111000.
    

    That would likely make the short be 0101011001111000 = 0x5678