Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shifting a negative value with literal is giving [-Wshift-negative-value] warning

Tags:

c

I am doing a bitwise left shift operation on negative number.

int main(void) {
    int count = 2;
    printf("%d\n", ~0<<count);
    printf("%d\n", ~0<<2); // warning:shifting a negative signed value is undefined [-Wshift-negative-value]
    return 0;
}

My doubt is why the warning is coming on compiling above code when integer literal is used in shifting and not when variable is used.

like image 899
Anand Barnwal Avatar asked Nov 01 '17 18:11

Anand Barnwal


People also ask

What happens when you bit shift a negative number?

For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used. The result of a right-shift of a signed negative number is implementation-dependent.

Is shifting right negative or positive?

A negative value indicates a shift to the right, and a positive value indicates a shift to the left. A vertical shift is a change in the y-intercept, or b-value.

What is negative shift count Python?

Python: negative shift counts are a run-time error. Fortran: ishft intrinsic function accepts positive and negative values for left and right shifts, respectively. Mathematica: BitShift[Left,Right] accept both positive and negative values.


1 Answers

Under C89, ones'-complement and sign-magnitude implementations were required to process left shifts of negative values in ways that may not have been the most logical on those platforms. For example, on a ones'-complement platform, C89 defined -1<<1 as -3. The authors of the Standard decided to correct this problem by allowing compiler writers to handle left shifts of negative numbers in any way they saw fit. The fact that they allowed that flexibility to all implementations including two's-complement ones shouldn't be taken to imply that they intended that two's-complement implementations to deviate from the C89 behavior. Much more likely, they intended and expected that the sensible behavior on two's-complement platforms would be sufficiently obvious that compiler writers would figure it out with or without a mandate.

Compilers often squawk about left-shifting negative constants by other constants because x<<y can be simplified when both x and y are constants, but such simplification would require performing the shift at compile time whether or not the code containing the shift is executed. By contrast, given someConstant << nonConstant, no simplification would usually be possible and thus the compiler would simply generate code that does the shift at run-time.

like image 114
supercat Avatar answered Oct 19 '22 16:10

supercat