I'm currently learning for a C++ examn. One of the questions in the practice examn is:
What is the output of this statement.
cout <<(11>>1)<<1<<endl;
As I see it. 11 holds the binary equivalent of
1011.
Shifting this binary number with 1 bit to the right makes it:
0101
Then shifting THAT number one to the left makes it
1010
Which evaluates to 10.
However, by running the same statement in my compiler it says the number evaluates to 51. Can someone explain this to me?
This is due to operator overloading.
cout <<(11>>1)<<1<<endl;
// ^ output operator
// ^ right shift
// ^ output operator
If you were to change the code to this, then your answer would be correct:
cout << ((11>>1) << 1) <<endl;
// brackets force left shift operator instead of output
cout << (11>>1) << 1 << endl;
becomes
cout << 5 << 1 <<endl;
The streaming meaning of <<
takes precedence over the shifting meaning. Therefore it prints a 5 followed by a 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With