Search code examples
c++bit-shift

What is the >> operator really doing in this C++ code?


I am following along with Programming: Principles and Practice Using C++, and I am messing with the "get from" (>>) operator from some code in the third chapter. Here is a minimal reproducible version.

#include<iostream>
using namespace std;

int main() {
    int first_num;
    int second_num;
    cout << "Enter a number: ";
    cin >> first_num;
    first_num >> second_num;
    cout << "second_num is now: " << second_num;
}

The output that I got was the following:

Enter a number: 12  
second_num is now: 4201200

I had thought that second_num would just get the value of first_num, but clearly not. What has happened here? I am assuming this is defaulting to a bitshift rather than the "get from" operator, but if second_num is not defined, how does the computer know how far to bit shift first_num?


Solution

  • The program has undefined behavior because you bitshift using second_num which is not initialized.

    first_num >> second_num  // right shift `second_num` bits
    

    Note that the operator >> you use above is not the same as the overload used to extract a value from std::cin.