开发者

Unsigned Short to Unsigned Long assignment

While assigning from long to short, LSB开发者_运维技巧 2 bytes is 0, where as MSB is filled with values from the func1() Algorithm values from stack. Why is this happening, why the compiler is trying to get these junk values to the MSB 2bytes?

#include <stdio.h>

unsigned short func1(void); // NB: function prototype !

int main(void)

{

     unsigned long int L = 0;

     unsigned short K = 0;

     L = func1();

      printf("%lu", L); // prints junk values

      K = L; 

      printf("%u", K);  // prints 0

     return 0;
}

unsigned short func1(void)

{

      unsigned short i = 0;

      // Algorithm Logic!!!

      return i; // returns 0
}


The specifier for unsigned long is lu. That for unsigned short is hu. You invoke UB by not using the proper specifiers.


There are a number of problems with your code - here is a fixed version which should behave correctly.

#include <stdio.h>

unsigned short func1(void); // NB: function prototype !

int main(void)
{
  unsigned long int L = 0;
  unsigned short K = 0;

  L = func1();
  printf("%lu", L);
  K = L; 
  printf("%u", K);

  return 0;
}

unsigned short func1(void)
{
   unsigned short i = 0;

   // Algorithm Logic!!!

   return i; // returns 0
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜