Reputation: 89
Why I am not getting warning like
shifting of negative number is not allowed
when I use the following code:
#include <stdio.h>
int main (){
int k = -5;
unsigned int shift = 2;
unsigned ans = (k >> shift);
printf("ans:%u\n",ans);
return 0;
}
Upvotes: 0
Views: 79
Reputation: 67584
right shift of the signed number is implementation defined. Most modern implementation will use the arithmetic shift (and the 2 complement numbers)
Upvotes: 0
Reputation: 29985
shifting of negative number is not allowed
This is not correct. Right shift on a negative number is allowed, though the result is implementation-defined.
Upvotes: 0
Reputation: 372832
In C, you are allowed to shift negative numbers. The result of the operation varies from system to system based on whether the compiler interprets the shift as an arithmetic shift or a logical shift. A logical shift fills the top bits of the result with 0s, and an arithmetic shift fills the top bits of the result with 1s if the original number was negative.
The result is what’s called implementation-defined, meaning that each compiler should document what specific behavior it’s going to use. So check your compiler’s documentation for more details.
The fact that this is implementation-defined might account for why there’s no warnings here. Shifting of a negative number is perfectly legal C code; it just doesn’t always mean the same thing on all systems.
Hope this helps!
Upvotes: 3