Home > front end >  What is the >> operator really doing in this C code?
What is the >> operator really doing in this C code?

Time:08-02

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?

CodePudding user response:

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.

CodePudding user response:

Indeed, there is undefined behavior in this piece of code. Please take a look at the cplusplus reference

Example here of how bitshifts are working:

#include<iostream>
using namespace std;
int main() {
   int a = 1, b = 3;
   
   // a right now is 00000001
   // Left shifting it by 3 will make it 00001000, ie, 8
   a = a << 3;
   cout << a << endl;
   
   // Right shifting a by 2 will make it 00000010, ie, 2
   a = a >> 2;
   cout << a << endl;
   return 0;
}

Which will output:

8
2
  • Related