0

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;
}
jailaxmi k
  • 89
  • 3
  • 11
  • 1
    In general compilers can't warn you about every possible problem in your code. But if you would say what compiler you're using, someone might have a suggestion for how to get a warning in this case. – Nate Eldredge Jun 18 '20 at 18:30
  • Who are what are you quoting with "shifting of negative number is not allowed"? – David Schwartz Jun 18 '20 at 18:31
  • 4
    Note the C standard doesn't say shifting a negative number is "not allowed"; it says that *the resulting value is implementation-defined*. – Nate Eldredge Jun 18 '20 at 18:32
  • who tolds you that c compiler or c language rules should warn you ??? – Adam Jun 18 '20 at 18:39

3 Answers3

3

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
0

right shift of the signed number is implementation defined. Most modern implementation will use the arithmetic shift (and the 2 complement numbers)

Arithmetic shift: enter image description here

0___________
  • 60,014
  • 4
  • 34
  • 74