-5
main()
{
   int i=-1,j=32,k;
   k=i<<j;
   printf("i=%d j=%d k=%d\n",i,j,k);
}

output:

i=-1 j=32,k=-1

If I am taking j=33 then k=-2 and if j=34 then k=-4.its repeating after 32 times left shift i.e if j=64,k becomes -1 and if j=65 then k=-2.but logically bit should be lost i.e output is 0.what is happening here.

Sorry for asking such a question. I am beginner so I'm unable to understand what the compiler does here. Can you explain?

Maxime Chéramy
  • 16,409
  • 7
  • 51
  • 73
DILIP
  • 1
  • 2

1 Answers1

1

You cannot count on getting a meaningful result when shifting a value by an amount equal to or greater than its size. From the standard:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

Jon
  • 413,451
  • 75
  • 717
  • 787