0

Possible Duplicate:
Left shifting with a negative shift count

Consider my code follows

int main()
{
    int k=1;
    k=k<<-1;
    printf("%d",k);
}

o/p

-2147483648

Why the output is like this.I know negative no's are stored in 2's complement but here is there any use of this concept of -2s complement.Kindly give me some idea.

Community
  • 1
  • 1
pradipta
  • 1,718
  • 2
  • 13
  • 24

3 Answers3

3

k << -1; // Before the OP edit

and

k = k<<-1;

These statements are undefined behavior in C.

Using a negative value in the right operand of the bitwise left or right shift operator is undefined behavior in C (see C99, 6.5.7).

ouah
  • 142,963
  • 15
  • 272
  • 331
2

The reason for the -2147483648 result - if you're testing this on an x86 processor - is that the shift count gets clamped to 31 (see "Intel Architecture Software Developer’s Manual Volume 2: Instruction Set Reference"). So you're getting 1<<31, which equals 0x80000000, which when printed as a signed 32-bit integer becomes -2147483648.

Michael
  • 57,169
  • 9
  • 80
  • 125
1

The result of a shift operation is undefined if the second operand is negative.

http://msdn.microsoft.com/en-us/library/f96c63ed%28v=vs.80%29.aspx
Why am I getting strange results bit-shifting by a negative value?

Community
  • 1
  • 1
Jeyaram
  • 9,158
  • 7
  • 41
  • 63