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?
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
.
Indeed, there is undefined behavior in this piece of code. Please take a look at thecplusplus 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.