Why offsetting a negative value with a literal gives a warning [-Wshift-negative-value]

I perform a bitwise left shift operation on a 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; } 

I doubt why a warning about compiling the above code occurs when an integer literal is used when shifting, and not when a variable is used.

+7
c
source share
1 answer

In accordance with C89, algorithms with one complement and a significant value were implemented in ways that may not have been the most logical on these platforms to perform left shifts of negative values. For example, on a platform with one add-on, C89 sets -1 <1 as -3. The authors of the Standard decided to fix this problem by allowing the authors of the compiler to process left shifts with negative numbers in any form convenient for them. The fact that they allow such flexibility for all implementations, including two “complementary” ones, should not imply that they assumed that the implementation of the two add-ons would be different from the behavior of C89. It is much more likely that they intended and expected that reasonable behavior on platforms with two additions would be obvious enough that compilers would figure this out with or without a mandate.

Compilers often twist relatively negative constants to the left of other constants, because x<<y can be simplified when both x and y are constants, but to simplify this, you will need to perform a shift during compilation, regardless of whether the code containing the shift is executed. In contrast, given someConstant << nonConstant , simplification would normally be impossible, and therefore, the compiler would simply generate code that performs the shift at runtime.

+2
source share

All Articles