Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading