Can someone please explain to me how the operators >> and << work?

It is very unclear on every explanation I have seen. People always say something like, it shifts the raw bits, as if that makes and sense.

http://msdn.microsoft.com/en-us/library/336xbhcz.aspx

That example wasn't helpful because I never use it for that purpose.
A left shift (<<) multiplies your number by 2n.
A right shift (>>) divides your number by 2n (and throws away the remainder).

If you look at the binary representation of a number, you see what is meant by bit-shifting:


0001 << 1 == 0010
0010 << 1 == 0100
0100 << 1 == 1000

1000 >> 2 == 0010
1000 >> 1 == 0100

etc.

Hope this helps.
How does cout >>"text" >> endl; work?
Ah, that's the other use of the operator. Streams override the << and/or >> operators to mean something different. There's plenty of documentation about streams on this site, and I'm sure there are other tutorials out there too. A search for "C++ stream operator" shou'd find you what you need.
The idea is that you can "overload" an operator for your own data types.

The shift operators, written << and >>, are defined over integer data types (like int and char).

However, cout is an std::ostream, which is not an integer, and it would make no sense to apply an arithmetic shift to a stream.

Even so, you can still create a definition for the operators. (Remember, operator overloads are actually just functions that get called when you use an operator on your data type. For example, you could write:

1
2
3
4
5
6
struct point
  {
  int x, y;
  point(): x( 0 ), y( 0 ) { }
  point( int x, int y ): x( x ), y( y ) { }
  };

If you wanted to add two points, you can write a function to do it:

1
2
3
4
point add( const point& a, const point& b )
  {
  return point( a.x + b.x, a.y + b.y );
  }
1
2
3
point p1, p2, p3;
...
p3 = add( p1, p2 );

However, it is prettier to make the '+' operator do it:

1
2
3
4
point operator + ( const point& a, const point& b )
  {
  return point( a.x + b.x, a.y + b.y );
  }
1
2
3
point p1, p2, p3;
...
p3 = p1 + p2;


The whole trick here is that the overloaded operator does not have to actually do what you think it will.
That's right. You could have written:

1
2
3
4
point operator + ( const point& a, const point& b )
  {
  return point( -7, a.x * b.x - b.y );
  }

But now, of course:
 
p3 = p1 + p2;  // Hey! This doesn't do what I think it should do! 


The standard library used the visual suggestion (common in shell scripting) that items will be "redirected" (or "piped") into the stream.

Hence, cout << "Hello world!\n"; suggests that the text string will be "directed" (or printed) into the output terminal (or file).

In this case it does make sense due to historical reasons. In general, however, you should use the principle of least surprise and make overloaded operators do what they say they will. Add should add, etc.

I hope this makes sense.
Topic archived. No new replies allowed.