Inconsistent behaviour for (1 << 32)
Hi,
I did encounter a strange problem in my C program, and traced it down;
it looks like I get different results for bit left shifts when the bit
count is a constant or a funtion-return value.
When doing (1 << 32) for a 32-bit-unsigned I expect to get 0; can I
assume this, or is this something I should never do? However, running
the attached code gives me two different outputs (1 0) when run, while I
expected it to print 0 0.
I use gcc 4.2.1 like this:
gcc -pedantic -std=c99 test.c -o test
When I turn on optimization, I get the expected results! Is this some
compiler problem or does my program trigger some undefined behaviour?
Thanks,
Daniel
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#define NUM_BITS ((unsigned short)(8*sizeof(unsigned)))
unsigned short getBits()
{
return NUM_BITS;
}
int main()
{
unsigned a=(1 << getBits());
unsigned b=(1 << NUM_BITS);
assert(NUM_BITS==getBits());
printf("%u %u\n", a, b);
return 0;
}
|