Search code examples
cbit-manipulationsignedoctal

Compiler dependency in right shift operator on signed types:


In the following code,

#include <stdio.h>
#include<conio.h>
main()
{
    int y=-01;
    y<<=3;
    printf("%d\n",y);
    y>>=3;
    printf("%d",y);
    getch();
}

I read in a book that while using the right shift operator on y, the signed bit may or may not be preserved depending on my compiler. Why is that? What is the concept behind this? Please elaborate.


Solution

  • Some processors have only an "unsigned" right shift (fills the sign bit with 0's) or a signed right shift (fills the size bit with copies of the current sign bit). Since some processors only have one or the other, but not both, the standard doesn't try to mandate one behavior or the other.

    For what it's worth, many (most?) current processors have instructions to do both. For example, the x86 includes both shr (logical shift right -- fills with 0's) and sar (arithmetic shift right -- fills with copies of the sign bit).