I am reading about the bit shift operation in C/C++ and I found this guide which describes both left shift and right shift operations. It states that
The right operand should not have a negative value or a value that is greater than or equal to the width in bits of the expression being shifted. The result of bitwise shifts on such values is unpredictable.
What exactly does this mean?
I did a test to see what would happen if I attempted to do a left shift of 10, -1, and 80 on an integer:
//Test.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myInt = 16;
int shifted;
cout << "Before left shift: " << myInt << endl;
shifted = myInt << 10;
cout << "After left shift 10: " << shifted << endl; //A
shifted = myInt << -1;
cout << "After left shift by -1: " << shifted << endl; //B
shifted = myInt << 88;
cout << "After left shift by 80: " << shifted << endl; //C
}
As expected, the output at A is 16384. At B, the output is 8, which seems to suggest that -1 left shift is equivalent to right shift by 1. At C, the output is 0. I'm not sure why that is.
So just how unpredictable are the results? Is it generally true that a negative left shift is equivalent to a right shift of the same absolute number of positions? Also, what exactly happens when the shift exceeds the width of the type?