开发者

Unsigned Short to Unsigned Long assignment

开发者 https://www.devze.com 2022-12-21 19:07 出处:网络
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

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

精彩评论

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

关注公众号