Possible Duplicate:
GCC left shift overflow
Consider the following minimal program.
#include <stdint.h>
#include <stdio.h>
int main()
{
uint32_t v = 1024;
v &= (((uint32_t)1 << 32) - 1);
printf("v = %u\n", v);
return 0;
}
This prints 1024
as I would expected compiling with GCC under MinGW. Because 1 shifted 32 times to the left is 0 again, thus 0-1 = -1 which is "1111....1111". This AND'ed with any value should return the same value again.
However, if I change the program to
#include <stdint.h>
#include <stdio.h>
int main()
{
unsigned int s = 32;
uint32_t v = 1024;
v &= (((uint32_t)1 << s) - 1);
printf("v = %u\n", v);
return 0;
}
The result printed is now 0
. Can someone explain this behaviour?
Shifting a 32-bit value by 32 bits is undefined behaviour in C. Don't do it.
Both are undefined behaviour, since the shift distance must be less than the bit-width of the type. With the constant, gcc's optimiser does what you expect, but with the variable, the shift is done at run time. Probably the shift distance is masked with 31, so no shift is done and 1 - 1 == 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With