I am trying to do left shift bit in c.
int a = 32;
printf("%d\n", ~0 << a);
printf("%d\n", ~0 << 32);
So I run above 2 printf()s, the result is different. I use dev-C++. I don't understand why is different. Please help me.
I am trying to do left shift bit in c.
int a = 32;
printf("%d\n", ~0 << a);
printf("%d\n", ~0 << 32);
So I run above 2 printf()s, the result is different. I use dev-C++. I don't understand why is different. Please help me.
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
That's from the C standard. The second you start using 32-bit shifts on a value 32 bits wide, all bets are off.
What's possibly happening is that the compiler is constant folding ~0 << 32
since this can be fully calculated at compile time.
The expression ~0 << a
can not be constant folded (unless it's a really clever compiler that can determine a
will always be 32).
That may account for any difference but, to be honest, there's nothing in the standard stopping the program from erasing your hard disk or creating a mini black hole in the CPU (other than the market reaction) since undefined behaviour is, well, undefined.
You're (probably) shifting by >=
the amount of bits in a type (likely int
is 32 bits on whatever system you're using). This is undefined behaviour - the compiler is allowed to emit code that does anything it wants.