'how to use shift operator in cout statement as it is overloaded

I am quite new to C++, I know that shift operator in C++ is overloaded. But as how we can do shift operation within printf statement in C can we do similar shift operation in cout statement.

c++


Solution 1:[1]

Well, just try it...

#include <iostream>

int main() {
    int k = 1;
    std::cout << (k << 1) << std::endl;  // Correct shifting - notice the parentheses
    std::cout << k << 1 << std::endl;    // Wrong
    return 0;
}

Output:

2
11

What matters here is the type of the variables used for the << operator.

The parentheses causes it to be int << int which is the bitwise shifting. Without the parentheses it will be ostream << int which will write the int to the stream.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1