Muhammad Fuzail
Muhammad Fuzail

Reputation: 29

When size is 64 bits then why shifting left 32 times give a zero

unsigned long long n=123;
printf("size of n:%d\n",sizeof(n)); //output of this line is "size of n:8"
n=n<<32;
printf("%u",n); //output of this line is "0"

why output is 0 when the size is 64bits output 0 is justified only if size is 32bits

Upvotes: 1

Views: 70

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

The program behaviour is undefined on two counts, and you're on thin ice on another point:

  1. Use "%zu" as the format specifier for the sizeof return type. Using '%d' wreaks havoc, particularly if you pass multiple arguments to printf.

  2. unsigned long long is at least 64 bits. That doesn't matter in your case but don't assume it's always 64 bits. And the format specifier needs to be %llu.

Reference: http://en.cppreference.com/w/c/io/fprintf

Upvotes: 4

n may be 64 bits, but your printf() call only expects 32 bits. This is undefined behavior. What appears to be happening in this particular case is that the remaining bits are cut off, and only the apparently low order 32 bits are displayed. Other platforms/compilers/machines might do something entirely different.

You can fix that by passing the correct integer type in the format string:

printf("%llu",n);

Upvotes: 4

Related Questions