jailaxmi k
jailaxmi k

Reputation: 89

Why does a C compiler not throw a warning when using bitshifting on negative value?

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

Answers (3)

0___________
0___________

Reputation: 67584

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

Upvotes: 0

Aykhan Hagverdili
Aykhan Hagverdili

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

templatetypedef
templatetypedef

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

Related Questions